Created
February 12, 2013 08:29
-
-
Save daifu/4760967 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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 ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>(); | |
| ArrayList<Integer> list=new ArrayList<Integer>(); | |
| Arrays.sort(num); | |
| getCombination(num,0,target,list,result); | |
| return result; | |
| } | |
| public void getCombination(int[] array, int start, int target, ArrayList<Integer>curList, ArrayList<ArrayList<Integer>> curResult) { | |
| if((start==array.length)|| (target<0))return; | |
| for(int i=start;i<array.length;i++) { | |
| if(i>start && (array[i]==array[i-1])) continue; | |
| curList.add(array[i]); | |
| if(target-array[i]==0) { | |
| curResult.add(new ArrayList<Integer>(curList)); | |
| } | |
| if(i<array.length-1) getCombination(array,i+1,target-array[i],curList,curResult); | |
| curList.remove(curList.size()-1); | |
| } | |
| return; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment