zoukankan      html  css  js  c++  java
  • 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<Integer> 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<Integer> 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);
            }
        }
    }
    
  • 相关阅读:
    获取物料批次特性取值BAPI
    获取域的固定值的函数:DD_DOMVALU…
    CJ20N中对WBS元素执行删除操作时触…
    SM30相关操作
    CL03对应的BAPI(根据类查特性)
    两个数值交换
    char*,string,float,int 转换
    字符串 分割
    C++ 关于I/O
    TCP
  • 原文地址:https://www.cnblogs.com/mapoos/p/13527592.html
Copyright © 2011-2022 走看看