组合总和二

解题思路:
和组合总和一样的思路。回溯。就是注意每一次起始索引要加一,还有要避免重复。
代码:
public IList<IList<int>> CombinationSum2(int[] candidates, int target)
{
IList<IList<int>> result = new List<IList<int>>();
IList<int> lgx = new List<int>();
int begin = 0;
Array.Sort(candidates);
DFS2(candidates, target, begin, lgx, result);
return result;
}//40. 组合总和 II。
public void DFS2(int[] candidates, int target, int begin, IList<int> lgx, IList<IList<int>> result)
{
if (target == 0)
{
result.Add(new List<int>(lgx));
return;
}
for (int i = begin; i < candidates.Length; i++)
{
if (target - candidates[i] < 0)
break;
if (i > begin && candidates[i] == candidates[i - 1])
continue;//避免选择重复的元素。
lgx.Add(candidates[begin]);
DFS2(candidates, target - candidates[i], i + 1, lgx, result);
lgx.RemoveAt(lgx.Count - 1);
}
}//回溯。


被折叠的 条评论
为什么被折叠?



