Created
September 3, 2015 18:49
-
-
Save cxtadment/1cebc2fccdedd57e35ee to your computer and use it in GitHub Desktop.
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
| public class Solution { | |
| /** | |
| * @param candidates: A list of integers | |
| * @param target:An integer | |
| * @return: A list of lists of integers | |
| */ | |
| public List<List<Integer>> combinationSum(int[] candidates, int target) { | |
| // write your code here | |
| List<List<Integer>> result = new ArrayList<>(); | |
| if (candidates == null || candidates.length == 0) { | |
| return result; | |
| } | |
| List<Integer> combination = new ArrayList<>(); | |
| Arrays.sort(candidates); | |
| combinationSumHelper(candidates, target, 0, result, combination); | |
| return result; | |
| } | |
| public void combinationSumHelper(int[] candidates, int target, int pos, List<List<Integer>> result, List<Integer> combination) { | |
| if (target == 0) { | |
| result.add(new ArrayList<Integer>(combination)); | |
| return; | |
| } | |
| for (int i = pos; i < candidates.length; i++) { | |
| if (target >= candidates[i]) { | |
| combination.add(candidates[i]); | |
| int restTarget = target - candidates[i]; | |
| combinationSumHelper(candidates, restTarget, i, result, combination); | |
| combination.remove(combination.size() - 1); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment