1. 程式人生 > >[Swift Weekly Contest 117]LeetCode967. 具有相同連續差異的數字 | Numbers With Same Consecutive Differences

[Swift Weekly Contest 117]LeetCode967. 具有相同連續差異的數字 | Numbers With Same Consecutive Differences

answer tput exp ted cut enc ever nat ces

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 }

[Swift Weekly Contest 117]LeetCode967. 具有相同連續差異的數字 | Numbers With Same Consecutive Differences