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. 1 <= N <= 9
  2. 0 <= K <= 9
class Solution {
    public int[] numsSameConsecDiff(int N, int K) {
        List<Integer> list = Arrays.asList(0,1,2,3,4,5,6,7,8,9);
        
        for(int i = 2; i <= N; i++) {
            List<Integer> tmp = new ArrayList();
            for(int j : list) {
                int x = j % 10;
                if(j > 0 && x + K < 10) tmp.add(j * 10 + K + x);
                if(j > 0 && K > 0 && x - K >= 0) tmp.add(j * 10 + x - K);
            }
            list = tmp;
        }
        int[] res = new int[list.size()];
        int i = 0;
        for(int j : list) res[i] =list.get(i++);
        return res;
    }
}

从要求出发,要求我们返回所有相邻位差为K的N位数。

那我们可以从0-9出发,采用类似bfs的做法,在每一位上进行筛选然后进去下一位。

具体筛选方法:既然要相邻位差,那我们先找到上一位最右侧的数(取模),然后±k看是否还符合要求(新生成的位≥0且<10),符合就添加到当前list中。每一位结束后更新一下list。

posted @ 2020-08-18 21:59  Schwifty  阅读(174)  评论(0)    收藏  举报