0967. Numbers With Same Consecutive Differences (M)

Numbers With Same Consecutive Differences (M)

题目

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

题意

求所有的N位数,使得其中每一个数中的每相邻两个位的数字之差为K。

思路

用回溯法去生成每一个这样的N位数。需要注意的坑是N=1时要考虑0,以及K=0时注意剪枝。


代码实现

Java

class Solution {
    public int[] numsSameConsecDiff(int N, int K) {
        List list = new ArrayList<>();
        for (int i = N == 1 ? 0 : 1; i < 10; i++) {
            dfs(0, i, 1, N, K, list);
        }
        int[] ans = new int[list.size()];
        int i = 0;
        for (int num : list) {
            ans[i++] = num;
        }
        return ans;
    }

    private void dfs(int num, int digit, int index, int N, int K, List list) {
        if (digit < 0 || digit > 9) {
            return;
        }
        num = num * 10 + digit;

        if (index == N) {
            list.add(num);
            return;
        }

        dfs(num, digit + K, index + 1, N, K, list);
        if (K > 0) {
            dfs(num, digit - K, index + 1, N, K, list);
        }
    }
}

你可能感兴趣的:(0967. Numbers With Same Consecutive Differences (M))