You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_backtracking/permutations_i.swift

51 lines
1.4 KiB

/**
* 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() {
//
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)")
}
}