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

51 lines
1.4 KiB
Swift
Raw Normal View History

/**
* File: permutations_i.swift
* Created Time: 2023-04-30
* Author: nuomi1 (nuomi1@qq.com)
*/
/* I */
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
//
if state.count == choices.count {
res.append(state)
return
}
//
for (i, choice) in choices.enumerated() {
2023-10-17 23:45:31 +08:00
//
if !selected[i] {
//
selected[i] = true
state.append(choice)
//
backtrack(state: &state, choices: choices, selected: &selected, res: &res)
// 退
selected[i] = false
state.removeLast()
}
}
}
/* I */
func permutationsI(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 PermutationsI {
/* Driver Code */
static func main() {
let nums = [1, 2, 3]
let res = permutationsI(nums: nums)
print("输入数组 nums = \(nums)")
print("所有排列 res = \(res)")
}
}