From dcc37da6034f3ad8166c9f06ee2ab75a3ad204e7 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Thu, 14 Dec 2023 10:01:34 +0800 Subject: [PATCH] =?UTF-8?q?Update0039.=E7=BB=84=E5=90=88=E7=BB=BC=E5=90=88?= =?UTF-8?q?=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0039.组合总和.md | 60 +++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) 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); + } + } +} +```