[Swift Weekly Contest 117]LeetCode967. 具有相同连续差异的数字 | Numbers With Same Consecutive Differences

[Swift Weekly Contest 117]LeetCode967. 具有相同连续差异的数字 | Numbers With Same Consecutive Differences,第1张

概述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 th

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 <= N <= 9 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 <n= 9 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...910             {11                 v.append(i)12             }13             return v14         }15         n = N16         k = K17         val = 018         dfs(0,0)19         v = v.sorted(by:>)20         return v21     }22     23     func dfs(_ cur:Int,_ pr:Int)24     {25         if cur == n26         {27             v.append(val)28             return29         }30         for i in 0...931         {32             if cur == 033             {34                 if i != 035                 {36                     val = i37                     dfs(cur + 1,i)38                 }39             }40             else41             {42                 val *= 10 43                 val += i44                 if abs(pr - i) == k45                 {46                     dfs(cur + 1,i)47                 }48                 val -= i49                 val /= 1050             }51         }52     }53 }
总结

以上是内存溢出为你收集整理的[Swift Weekly Contest 117]LeetCode967. 具有相同连续差异的数字 | Numbers With Same Consecutive Differences全部内容,希望文章能够帮你解决[Swift Weekly Contest 117]LeetCode967. 具有相同连续差异的数字 | Numbers With Same Consecutive Differences所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1021846.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存