加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[Swift Weekly Contest 117]LeetCode967. 具有相同连续差异的数

发布时间:2020-12-14 05:08:08 所属栏目:百科 来源:网络整理
导读: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,?

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。

注意,答案中的每个数字都不能有前导零,除了数字0本身。例如,01有一个前导零,它是无效的,但0是有效的。

您可以按任何顺序返回答案。

例1:

输入:n=3,k=7

输出:【181292707818929】

说明:请注意,070不是有效数字,因为它有前导零。

例2:

输入:n=2,k=1

输出:【10、12、21、23、32、34、43、45、54、56、65、67、76、78、87、89、98】

注:

  1. 1 <n= 9
  2. 0 <= k<=9

28ms

 1 class Solution {
 2     var v:[Int] = [Int]()
 3     var n:Int = 0
 4     var k:Int = 0
 5     var val:Int = 0
 6     func numsSameConsecDiff(_ N: Int,_ K: Int) -> [Int] {
 7         if N == 1
 8         {
 9             for i in 0...9
10             {
11                 v.append(i)
12             }
13             return v
14         }
15         n = N
16         k = K
17         val = 0
18         dfs(0,0)
19         v = v.sorted(by:>)
20         return v
21     }
22     
23     func dfs(_ cur:Int,_ pr:Int)
24     {
25         if cur == n
26         {
27             v.append(val)
28             return
29         }
30         for i in 0...9
31         {
32             if cur == 0
33             {
34                 if i != 0
35                 {
36                     val = i
37                     dfs(cur + 1,i)
38                 }
39             }
40             else
41             {
42                 val *= 10 
43                 val += i
44                 if abs(pr - i) == k
45                 {
46                     dfs(cur + 1,i)
47                 }
48                 val -= i
49                 val /= 10
50             }
51         }
52     }
53 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读