diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index 37d5614e..81558cc1 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -598,6 +598,66 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> CombinationSum(int[] candidates, int target) + { + BackTracking(candidates, target, 0, 0); + return res; + } + public void BackTracking(int[] candidates, int target, int start, int sum) + { + if (sum > target) return; + if (sum == target) + { + res.Add(new List(path)); + return; + } + for (int i = start; i < candidates.Length; i++) + { + sum += candidates[i]; + path.Add(candidates[i]); + BackTracking(candidates, target, i, sum); + sum -= candidates[i]; + path.RemoveAt(path.Count - 1); + } + } +} + +// 剪枝优化 +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> CombinationSum(int[] candidates, int target) + { + Array.Sort(candidates); + BackTracking(candidates, target, 0, 0); + return res; + } + public void BackTracking(int[] candidates, int target, int start, int sum) + { + if (sum > target) return; + if (sum == target) + { + res.Add(new List(path)); + return; + } + for (int i = start; i < candidates.Length && sum + candidates[i] <= target; i++) + { + sum += candidates[i]; + path.Add(candidates[i]); + BackTracking(candidates, target, i, sum); + sum -= candidates[i]; + path.RemoveAt(path.Count - 1); + } + } +} +```