美文网首页Swift LeetCode
Swift LeetCode 系列之46: permutatio

Swift LeetCode 系列之46: permutatio

作者: TimberTang | 来源:发表于2017-11-22 10:41 被阅读26次

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: permutatio

    本文链接:https://www.haomeiwen.com/subject/dbrnvxtx.html