[Backtracking] [leetcode] n-digits where the difference between adjacent digits is k

topic:

Returns all non-negative integers whose length is n and the absolute value of the difference between every two consecutive digits is k.

Note that, except for the number 0 itself, every number in the answer cannot have leading zeros. For example, 01 has a leading zero, so it is invalid; but 0 is valid.

You can return the answers 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 zeros.

prompt:

  • 2 <= n <= 9
  • 0 <= k <= 9

source:

967. Successive numbers with the same difference

Problem-solving ideas: backtracking

Define an array path to store n digits

  • The result meets the condition: when the size of path is equal to n
  • Recursive calling conditions: the last number in path +k or -k. Note that when k=0, the same two conditions will lead to duplicate results.
class Solution {
public:
    vector<int> result;
    vector<int> path;
    vector<int> numsSameConsecDiff(int n, int k) {
        for (int i = 1; i <= 9; i++) {
            path.push_back(i);
            back(n, k);
            path.pop_back();
        }
        return result;
    }
    void back(int n, int k) {
        if (path.size() == n) {
            int v = path[0];
            for (int i = 1; i < n; i++) {
                v = v * 10 + path[i];
            }
            result.push_back(v);
            return;
        }
        int pre = path[path.size() - 1];
        if (pre + k < 10) {
            path.push_back(pre+k);
            back(n, k);
            path.pop_back();
        }
        if (k!=0 && pre - k >= 0) {
            path.push_back(pre-k);
            back(n, k);
            path.pop_back();
        }
    }
};

 

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/115129657