967. 连续差相同的数字
难度中等
返回所有长度为 N 且满足其每两个连续位上的数字之间的差的绝对值为 K 的非负整数。
请注意,除了数字 0 本身之外,答案中的每个数字都不能有前导零。例如,01 因为有一个前导零,所以是无效的;但 0 是有效的。
你可以按任何顺序返回答案。
示例 1:
输入:N = 3, K = 7
输出:[181,292,707,818,929]
解释:注意,070 不是一个有效的数字,因为它有前导零。
示例 2:
输入:N = 2, K = 1
输出:[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
提示:
1.
1 <= N <= 9
2.
0 <= K <= 9
思路1.0:
以1–9这几个数字为起点向后DFS,过程中找到的数字全部存在vector rst中
代码1.0:
class Solution {
public:
vector<int> ans;
void DFS(const int& node, const int& pos, const int& k, int rst) {
//构建当前位
rst += node * pow(10, pos - 1);
//构建完毕,压入全局容器
if (pos == 1) {
ans.push_back(rst);
return;
}
if (k == 0) {
DFS(node, pos - 1, k, rst);
return;
}
//确定下一位
if ((node + k) <= 9) {
DFS(node + k, pos - 1, k, rst);
}
if ((node - k) >= 0) {
DFS(node - k, pos - 1, k, rst);
}
}
vector<int> numsSameConsecDiff(int n, int k) {
for (int i = 1; i <= 9; ++i) {
DFS(i, n, k, 0);
}
return ans;
}
};