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)
        }
    }
    
}
    原文作者:TimberTang
    原文地址: https://www.jianshu.com/p/46ee5af15ca0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞