Update0039.组合综合,添加C#

This commit is contained in:
eeee0717
2023-12-14 10:01:34 +08:00
parent c14df2f577
commit dcc37da603

View File

@ -598,6 +598,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>> 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<int>(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<IList<int>> res = new List<IList<int>>();
public IList<int> path = new List<int>();
public IList<IList<int>> 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<int>(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);
}
}
}
```
<p align="center">