hello-algo/zh-hant/codes/swift/chapter_backtracking/subset_sum_i_naive.swift

52 lines
1.6 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: subset_sum_i_naive.swift
* Created Time: 2023-07-02
* Author: nuomi1 (nuomi1@qq.com)
*/
/* I */
func backtrack(state: inout [Int], target: Int, total: Int, choices: [Int], res: inout [[Int]]) {
// target
if total == target {
res.append(state)
return
}
//
for i in choices.indices {
// target
if total + choices[i] > target {
continue
}
// total
state.append(choices[i])
//
backtrack(state: &state, target: target, total: total + choices[i], choices: choices, res: &res)
// 退
state.removeLast()
}
}
/* I */
func subsetSumINaive(nums: [Int], target: Int) -> [[Int]] {
var state: [Int] = [] //
let total = 0 //
var res: [[Int]] = [] //
backtrack(state: &state, target: target, total: total, choices: nums, res: &res)
return res
}
@main
enum SubsetSumINaive {
/* Driver Code */
static func main() {
let nums = [3, 4, 5]
let target = 9
let res = subsetSumINaive(nums: nums, target: target)
print("輸入陣列 nums = \(nums), target = \(target)")
print("所有和等於 \(target) 的子集 res = \(res)")
print("請注意,該方法輸出的結果包含重複集合")
}
}