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/zh-hant/codes/swift/chapter_backtracking/permutations_i.swift

51 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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