From d3e61f36abf8b40fa9afac4e7c414f13d8bfcec7 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 12 Dec 2023 09:20:04 +0800 Subject: [PATCH] =?UTF-8?q?Update0216.=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8C?= =?UTF-8?q?3=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/0216.组合总和III.md | 61 +++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index c0cb8860..ac28f9fc 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -633,7 +633,66 @@ object Solution { } } ``` - +### C# +```csharp +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> CombinationSum3(int k, int n) + { + BackTracking(k, n, 0, 1); + return res; + } + public void BackTracking(int k, int n, int sum, int start) + { + if (path.Count == k) + { + if (sum == n) + res.Add(new List(path)); + return; + } + for (int i = start; i <= 9; i++) + { + sum += i; + path.Add(i); + BackTracking(k, n, sum, i + 1); + sum -= i; + path.RemoveAt(path.Count - 1); + } + } +} +// 剪枝 +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> CombinationSum3(int k, int n) + { + BackTracking(k, n, 0, 1); + return res; + } + public void BackTracking(int k, int n, int sum, int start) + { + if (sum > n) + return; + if (path.Count == k) + { + if (sum == n) + res.Add(new List(path)); + return; + } + for (int i = start; i <= 9 - (k - path.Count) + 1; i++) + { + sum += i; + path.Add(i); + BackTracking(k, n, sum, i + 1); + sum -= i; + path.RemoveAt(path.Count - 1); + } + } +} +```