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...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 }
原文地址:https://www.cnblogs.com/strengthen/p/10201442.html
时间: 2024-08-30 16:30:23