[Swift Weekly Contest 108]LeetCode932. 漂亮數組 | Beautiful Array
阿新 • • 發佈:2018-10-28
eat 示例 clas 訪問 -o 分支 -i it is perm
For some fixed N
, an array A
is beautiful if it is a permutation of the integers 1, 2, ..., N
, such that:
For every i < j
, there is no k
with i < k < j
such that A[k] * 2 = A[i] + A[j]
.
Given N
, return any beautiful array A
. (It is guaranteed that one exists.)
Example 1:
Input: 4
Output: [2,1,4,3]
Example 2:
Input: 5
Output: [3,1,2,5,4]
Note:
1 <= N <= 1000
對於某些固定的 N
,如果數組 A
是整數 1, 2, ..., N
組成的排列,使得:
對於每個 i < j
,都不存在 k
滿足 i < k < j
使得 A[k] * 2 = A[i] + A[j]
。
那麽數組 A
是漂亮數組。
給定 N
,返回任意漂亮數組 A
(保證存在一個)。
示例 1:
輸入:4 輸出:[2,1,4,3]
示例 2:
輸入:5 輸出:[3,1,2,5,4]
提示:
1 <= N <= 1000
16ms
1 class Solution { 2 func beautifulArray(_ N: Int) -> [Int] { 3 var a:[Int] = [Int](repeating: 0,count: N) 4 dfs(1, 0, N, &a,0) 5 for i in 0..<N 6 { 7 a[i] += 1 8 } 9 return a 10 } 11 //深度優先搜索。DFS即Depth First Search.12 //對每一個可能的分支路徑深入到不能再深入為止,而且每個節點只能訪問一次 13 func dfs(_ d:Int,_ m:Int,_ n: Int,_ a:inout [Int],_ off:Int) -> Int 14 { 15 var off = off 16 if m >= n {return off} 17 if m + d >= n 18 { 19 a[off] = m 20 off += 1 21 return off 22 } 23 for i in 0..<2 24 { 25 off = dfs(d*2, m+d*i, n, &a, off) 26 } 27 return off 28 } 29 }
[Swift Weekly Contest 108]LeetCode932. 漂亮數組 | Beautiful Array