Swift LeetCode 系列之46: permutations

https://leetcode.com/problems/permutations/description/
笨方法采用了递归的方式

class Solution {
    var res = [[Int]]()
    var n = 0
    func permute(_ nums: [Int]) -> [[Int]] {
        let nums = nums
        n = nums.count
        perm(nums, i:0)
        return res
    }
    
    func perm(_ num: [Int], i: Int) {
        var num = num
        if i == n {
            res.append(num) 
        }
        for j in i ..< n {
            num.swapAt(i, j)
            perm(num, i:i + 1) 
            num.swapAt(j, i)
        }
    }
    
}

你可能感兴趣的:(Swift LeetCode 系列之46: permutations)