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.
关键词:深度遍历
思路:
- N是一个数字的位数,相邻的两个位数的数相差K。当N=1,就是所有数字都是个位数,这样是从0开始。否则,从1开始。
- 画tree: 假设N 大于1, 从1开始做循环,1为root,分成两个子树,-K 和+K。满足条件,进而dfs,直到当前str长度到N。
- 时间复杂度是O(n*2^n)
var numsSameConsecDiff = function(N, K) {
if (N < 1) return []; //no digits for num
let res = [];
for (let i = 0; i < 10; i++){ //each digit 1~9
if (N > 1 && i == 0) continue; //if row > 1(more one digits) and also when i = 0 skip eg. N=1 K=1
dfs(`${i}`);
}
function dfs(digit){
if (digit.length == N){
res.push(Number(digit));
return;
}
let last = Number(digit[digit.length-1]); //last character in cur string
if (last - K >= 0) dfs(`${digit}${last-K}`); //valid, then doing dfs
if ((last + K <= 9) && (K > 0)) dfs(`${digit}${last+K}`); //eg.N=2,K=0, will duplicate
}
return res;
};