hello-algo/codes/swift/chapter_backtracking/subset_sum_ii.swift
nuomi1 7359a7cb4b
Review Swift codes (#1150)
* feat(swift): review for chapter_computational_complexity

* feat(swift): review for chapter_data_structure

* feat(swift): review for chapter_array_and_linkedlist

* feat(swift): review for chapter_stack_and_queue

* feat(swift): review for chapter_hashing

* feat(swift): review for chapter_tree

* feat(swift): add codes for heap article

* feat(swift): review for chapter_heap

* feat(swift): review for chapter_graph

* feat(swift): review for chapter_searching

* feat(swift): review for chapter_sorting

* feat(swift): review for chapter_divide_and_conquer

* feat(swift): review for chapter_backtracking

* feat(swift): review for chapter_dynamic_programming

* feat(swift): review for chapter_greedy

* feat(swift): review for utils

* feat(swift): update ci tool

* feat(swift): trailing closure

* feat(swift): array init

* feat(swift): map index
2024-03-20 21:15:39 +08:00

58 lines
2 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_ii.swift
* Created Time: 2023-07-02
* Author: nuomi1 (nuomi1@qq.com)
*/
/* II */
func backtrack(state: inout [Int], target: Int, choices: [Int], start: Int, res: inout [[Int]]) {
// target
if target == 0 {
res.append(state)
return
}
//
// start
// start
for i in choices.indices.dropFirst(start) {
// target
// target
if target - choices[i] < 0 {
break
}
//
if i > start, choices[i] == choices[i - 1] {
continue
}
// target, start
state.append(choices[i])
//
backtrack(state: &state, target: target - choices[i], choices: choices, start: i + 1, res: &res)
// 退
state.removeLast()
}
}
/* II */
func subsetSumII(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 SubsetSumII {
/* Driver Code */
static func main() {
let nums = [4, 4, 5]
let target = 9
let res = subsetSumII(nums: nums, target: target)
print("输入数组 nums = \(nums), target = \(target)")
print("所有和等于 \(target) 的子集 res = \(res)")
}
}