JS Leetcode967.Numbers With Same Consecutive Differences

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.
关键词:深度遍历
思路

  1. N是一个数字的位数,相邻的两个位数的数相差K。当N=1,就是所有数字都是个位数,这样是从0开始。否则,从1开始。
  2. 画tree: 假设N 大于1, 从1开始做循环,1为root,分成两个子树,-K 和+K。满足条件,进而dfs,直到当前str长度到N。
  3. 时间复杂度是O(n*2^n)
    dfs
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;
}; 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值