mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update0216.组合总和3,添加C#
This commit is contained in:
@ -633,7 +633,66 @@ object Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### C#
|
||||
```csharp
|
||||
public class Solution
|
||||
{
|
||||
public IList<IList<int>> res = new List<IList<int>>();
|
||||
public IList<int> path = new List<int>();
|
||||
public IList<IList<int>> 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<int>(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<IList<int>> res = new List<IList<int>>();
|
||||
public IList<int> path = new List<int>();
|
||||
public IList<IList<int>> 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<int>(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user