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

54 lines
1.7 KiB
Swift
Raw Normal View History

/**
* File: subset_sum_i.swift
* Created Time: 2023-07-02
* Author: nuomi1 (nuomi1@qq.com)
*/
/* I */
func backtrack(state: inout [Int], target: Int, choices: [Int], start: Int, res: inout [[Int]]) {
// target
if target == 0 {
res.append(state)
return
}
//
// start
for i in choices.indices.dropFirst(start) {
// target
// target
if target - choices[i] < 0 {
break
}
// target, start
state.append(choices[i])
//
backtrack(state: &state, target: target - choices[i], choices: choices, start: i, res: &res)
// 退
state.removeLast()
}
}
/* I */
func subsetSumI(nums: [Int], target: Int) -> [[Int]] {
var state: [Int] = [] //
let nums = nums.sorted() // nums
let start = 0 //
var res: [[Int]] = [] //
backtrack(state: &state, target: target, choices: nums, start: start, res: &res)
return res
}
@main
enum SubsetSumI {
/* Driver Code */
static func main() {
let nums = [3, 4, 5]
let target = 9
let res = subsetSumI(nums: nums, target: target)
print("输入数组 nums = \(nums), target = \(target)")
print("所有和等于 \(target) 的子集 res = \(res)")
}
}