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

50 lines
1.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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