本文共 1416 字,大约阅读时间需要 4 分钟。
Combination Sum II
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:
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 List
> combinationSum2(int[] candidates, int target) { List
> finalList = new ArrayList
>(); Arrays.sort(candidates); comb (candidates,0, target, finalList, new ArrayList ()); return finalList; } public void comb (int[] candidates,int num, int target, List
> finalList, ArrayList array){ if(target==0){ if(!finalList.contains(array)){ // No repeat solutions finalList.add(array); return; } } if(target<0){ // solutions not accurate return; } for(int i = num;i< candidates.length;i++){ if(candidates[num]>target){ continue; } ArrayList newArray = (ArrayList ) array.clone(); newArray.add(candidates[i]); if(i<=candidates.length){ comb(candidates,i+1,target-candidates[i],finalList,newArray); } // recursion to check the rest of the list } return; }}
转载地址:http://ypuni.baihongyu.com/