Skip to content

Latest commit

 

History

History

967

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Return all non-negative integers of length N such that the absolute difference between every two consecutive digits is K.

Note that every number in the answer must not have leading zeros except for the number 0 itself. For example, 01 has one leading zero and is invalid, but 0 is valid.

You may return the answer in any order.

 

Example 1:

Input: N = 3, K = 7
Output: [181,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.

Example 2:

Input: N = 2, K = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

 

Note:

  1. 1 <= N <= 9
  2. 0 <= K <= 9

Related Topics:
Dynamic Programming

Solution 1.

// OJ: https://leetcode.com/problems/numbers-with-same-consecutive-differences/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
    vector<int> ans;
    void dfs(int num, int i, int N, int K) {
        if (i == N) {
            ans.push_back(num);
            return;
        }
        if (num % 10 + K <= 9) dfs(num * 10 + (num % 10 + K), i + 1, N, K);
        if (K != 0 && num % 10 - K >= 0) dfs(num * 10 + (num % 10 - K), i + 1, N, K);
    }
public:
    vector<int> numsSameConsecDiff(int N, int K) {
        for (int i = N == 1 ? 0 : 1; i <= 9; ++i) dfs(i, 1, N, K);
        return ans;
    }
};