1. 程式人生 > 實用技巧 >967. Numbers With Same Consecutive Differences

967. Numbers With Same Consecutive Differences

Return allnon-negativeintegers of lengthNsuch that the absolute difference between every two consecutive digits isK.

Note thateverynumber in the answermust nothave leading zerosexceptfor the number0itself. For example,01has one leading zero and is invalid, but0is 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。