mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Update0040.组合总和2,添加C#
This commit is contained in:
@ -773,7 +773,39 @@ object Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
### C#
|
||||
```csharp
|
||||
public class Solution
|
||||
{
|
||||
public List<IList<int>> res = new List<IList<int>>();
|
||||
public List<int> path = new List<int>();
|
||||
public IList<IList<int>> 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<int>(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user