mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-24 20:52:16 +08:00
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
61 lines
2.4 KiB
C#
61 lines
2.4 KiB
C#
/**
|
|
* File: subset_sum_ii.cs
|
|
* Created Time: 2023-06-25
|
|
* Author: hpstory (hpstory1024@163.com)
|
|
*/
|
|
|
|
namespace hello_algo.chapter_backtracking;
|
|
|
|
public class subset_sum_ii {
|
|
/* Backtracking: subset sum II */
|
|
void Backtrack(List<int> state, int target, int[] choices, int start, List<List<int>> res) {
|
|
// Record a solution when the subset reaches the original target (remaining target is 0)
|
|
if (target == 0) {
|
|
res.Add(new List<int>(state));
|
|
return;
|
|
}
|
|
// Iterate over all choices
|
|
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
|
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
|
|
for (int i = start; i < choices.Length; i++) {
|
|
// Pruning 1: exit the loop if this choice would exceed the remaining target
|
|
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
|
|
if (target - choices[i] < 0) {
|
|
break;
|
|
}
|
|
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
|
|
if (i > start && choices[i] == choices[i - 1]) {
|
|
continue;
|
|
}
|
|
// Try: make a choice and update target and start
|
|
state.Add(choices[i]);
|
|
// Proceed to the next choice
|
|
Backtrack(state, target - choices[i], choices, i + 1, res);
|
|
// Backtrack: undo the choice and restore the previous state
|
|
state.RemoveAt(state.Count - 1);
|
|
}
|
|
}
|
|
|
|
/* Solve subset sum II */
|
|
List<List<int>> SubsetSumII(int[] nums, int target) {
|
|
List<int> state = []; // State (subset)
|
|
Array.Sort(nums); // Sort nums
|
|
int start = 0; // Starting index for iteration
|
|
List<List<int>> res = []; // Result list (list of subsets)
|
|
Backtrack(state, target, nums, start, res);
|
|
return res;
|
|
}
|
|
|
|
[Test]
|
|
public void Test() {
|
|
int[] nums = [4, 4, 5];
|
|
int target = 9;
|
|
List<List<int>> res = SubsetSumII(nums, target);
|
|
Console.WriteLine("Input array nums = " + string.Join(", ", nums) + ", target = " + target);
|
|
Console.WriteLine("All subsets with sum " + target + " : res = ");
|
|
foreach (var subset in res) {
|
|
PrintUtil.PrintList(subset);
|
|
}
|
|
}
|
|
}
|