【LeetCode 967】 Numbers With Same Consecutive Differences

题目描述

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 <= N <= 9
0 <= K <= 9

思路

DFS,搜索数字位数,下一个数字比上一个数字差7。

代码

class Solution {
public:
    vector<int> numsSameConsecDiff(int N, int K) {
        dfs(N, K, 0, 0, 0);
        return ans;
    }
    
private:
    vector<int> ans;
    void dfs(int N, int K, long long cur, int cnt, int pre) {
        if (cnt == N) {
            ans.push_back(cur);
            return;
        }
        for (int i=0; i<10; ++i) {
            if (cnt ==1 && pre == 0) continue;
            if (cnt > 0 && abs(i-pre) != K) continue;
            dfs(N, K, cur*10+i, cnt+1, i);
        }
        return;
    } 
};
发布了323 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104943807