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);
            }
        }
    }
    
  • 相关阅读:
    基于ubuntu10.04的gccarm安装
    面向连接和非面向连接
    多址技术与复用技术
    NAT——网络地址转换
    IP地址与子网掩码的关系
    ISO的7层模型
    比特率与波特率的比较
    C#中GUID的使用
    iframe刷新父页面
    javascript 获取控件坐标
  • 原文地址:https://www.cnblogs.com/mapoos/p/13527592.html
Copyright © 2011-2022 走看看