Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5
and target 8
,
A solution set is: [1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
public class Solution { public IList<IList<int>> CombinationSum2(int[] candidates, int target) { List<IList<int>> result = new List<IList<int>>(); List<int> res=new List<int>(); Array.Sort(candidates); calulate(candidates,,target,res,result); return result; } void calulate(int[] candidates, int cur,int target,List<int> res,List<IList<int>> result) { ) { result.Add(new List<int>(res)); return; } ) { return; } for(int i=cur;i<candidates.Length;i++) { ]) continue; res.Insert(res.Count,candidates[i]); calulate(candidates,i+,target-candidates[i],res,result); res.RemoveAt(res.Count-); } } }
1 这个算法可以非常高效的计算出结果。
2 这个算法是在方法中调用方法本身。