46. 全排列
2022-07-18 本文已影响0人
邦_
func permute(_ nums: [Int]) -> [[Int]] {
let len = nums.count
var exitArray = Array.init(repeating: 0, count: len)
var tempArray = Array.init(repeating: 0, count: len)
var ans = Array<Array<Int>>()
dfs(0,nums,&tempArray, &exitArray,&ans)
return ans
}
func dfs (_ index:Int,_ nums:[Int],_ tempArray:inout [Int],_ exitArray: inout [Int],_ ans: inout [[Int]]) {
let len = nums.count
if index == len {
ans.append(tempArray)
return
}
for i in 0..<len {
if exitArray[i] == 0 {
tempArray[index] = nums[i]
exitArray[i] = 1
dfs(index + 1,nums,&tempArray,&exitArray,&ans)
//能走到这一行说明走到底了
exitArray[i] = 0
}
}
}
优化版本
func permute(_ nums: [Int]) -> [[Int]] {
var tempNums = nums
var ans = Array<Array<Int>>()
dfs(0,&tempNums,&ans)
return ans
}
func dfs (_ index:Int,_ nums:inout [Int],_ ans: inout [[Int]]) {
let len = nums.count
if index == len {
ans.append(Array.init(nums))
return
}
for i in index..<len {
nums.swapAt(index, i)
dfs(index + 1,&nums,&ans)
nums.swapAt(index, i)
}
}