算法 - 回溯04(Swift版本)

62 阅读1分钟

题目1:491.递增子序列

讲解
leetcode

思路:去重逻辑有变化,必须用一个集合来统计本层使用过哪些元素。

可以再回顾一下 回溯3 里对于树层去重的理解。

另外: 如果打算使用map, 优先可以考虑下是否可以使用数组。


// @lc code=start
class Solution {
    var result = [[Int]]()
    var set = [Int]()
    func findSubsequences(_ nums: [Int]) -> [[Int]] {
        findSubsequencesRecursive(nums, 0)
        return result
    }

    func findSubsequencesRecursive(_ nums: [Int], _ start: Int) {
        if set.count >= 2 {result.append(set) }
        if start == nums.count { 
            return 
        }
        var used = Array(repeating: 0, count: 201)
        for i in start..<nums.count {
            let num = nums[i]
            // 递增
            if let pre = set.last, num < pre {
                continue
            }
            // 树层去重, 因为不能排序,所以只能使用used map做去重
            if used[num + 100] ?? 0 == 1 {
                continue
            }
            used[num + 100] = 1
            set.append(num)
            findSubsequencesRecursive(nums, i + 1)
            set.removeLast()
        }
    }
}
// @lc code=end

题目2:46.全排列

讲解
leetcode


// @lc code=start
class Solution {
    func permute(_ nums: [Int]) -> [[Int]] {
        var result = [[Int]]()
        var set = [Int]()
        var used = [Bool](repeating: false, count: nums.count) // 记录path中已包含的元素
        func backtracking() {
            if set.count == nums.count {
                result.append(set)
                return
            }
            for i in 0..<nums.count {
                let num = nums[i]
                if used[i] { continue }
                used[i] = true
                set.append(num)
                backtracking()
                set.removeLast()
                used[i] = false
            }
        }
        backtracking()
        return result
    }
}
// @lc code=end

题目3:47.全排列 II

讲解
leetcode

配图好理解多了,需要看图说话。

// @lc code=start
class Solution {
    func permuteUnique(_ nums: [Int]) -> [[Int]] {
        var result = [[Int]]()
        var set = [Int]()
        let nums = nums.sorted()
        var used = Array(repeating: false, count: nums.count)
        func backtracking() {
            if set.count == nums.count { 
                result.append(set)
                return 
            }
            for i in 0..<nums.count {
                if used[i] { continue }
                let num = nums[i]
                if i > 0, num == nums[i-1], used[i - 1] == false { continue }
                used[i] = true
                set.append(num)
                backtracking()
                used[i] = false
                set.removeLast()
            }
        }   
        backtracking()
        return result
    }
}
// @lc code=end

题目4:332.重新安排行程

讲解
leetcode

有序字典在swift中如果呈现 是个需要考虑的问题。