hello-algo/codes/swift/chapter_backtracking/permutations_ii.swift

53 lines
1.6 KiB
Swift
Raw Normal View History

/**
* File: permutations_ii.swift
* Created Time: 2023-04-30
* Author: nuomi1 (nuomi1@qq.com)
*/
/* II */
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
//
if state.count == choices.count {
res.append(state)
return
}
//
var duplicated: Set<Int> = []
for (i, choice) in choices.enumerated() {
//
if !selected[i], !duplicated.contains(choice) {
//
duplicated.insert(choice) //
selected[i] = true
state.append(choice)
//
backtrack(state: &state, choices: choices, selected: &selected, res: &res)
// 退
selected[i] = false
state.removeLast()
}
}
}
/* II */
func permutationsII(nums: [Int]) -> [[Int]] {
var state: [Int] = []
var selected = Array(repeating: false, count: nums.count)
var res: [[Int]] = []
backtrack(state: &state, choices: nums, selected: &selected, res: &res)
return res
}
@main
enum PermutationsII {
/* Driver Code */
static func main() {
let nums = [1, 2, 3]
let res = permutationsII(nums: nums)
print("输入数组 nums = \(nums)")
print("所有排列 res = \(res)")
}
}