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.
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.
/* *
* F i l e : p e r m u t a t i o n s _ i i . s w i f t
* C r e a t e d T i m e : 2 0 2 3 - 0 4 - 3 0
* A u t h o r : n u o m i 1 ( n u o m i 1 @ q q . c o m )
*/
/* 回 溯 算 法 : 全 排 列 I I */
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 ( )
}
}
}
/* 全 排 列 I I */
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 {
/* D r i v e r C o d e */
static func main ( ) {
let nums = [ 1 , 2 , 3 ]
let res = permutationsII ( nums : nums )
print ( " 输入数组 nums = \( nums ) " )
print ( " 所有排列 res = \( res ) " )
}
}