mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Update0039.组合综合,添加C#
This commit is contained in:
@ -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">
|
||||
|
Reference in New Issue
Block a user