From 2cd982fd0dd478fb20989ee2dd8c1d28377f5829 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Fri, 15 Dec 2023 10:36:34 +0800 Subject: [PATCH] =?UTF-8?q?Update0040.=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8C?= =?UTF-8?q?2=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/0040.组合总和II.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 33e4a46f..994b04b8 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -773,7 +773,39 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public List> res = new List>(); + public List path = new List(); + public IList> CombinationSum2(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++) + { + if (i > start && candidates[i] == candidates[i - 1]) continue; + sum += candidates[i]; + path.Add(candidates[i]); + BackTracking(candidates, target, i + 1, sum); + sum -= candidates[i]; + path.RemoveAt(path.Count - 1); + } + } +} +```