Created
October 10, 2018 23:57
-
-
Save hsaputra/6ab49c77d140b84cc81ca4c34f4a306b to your computer and use it in GitHub Desktop.
Combination Sum - https://leetcode.com/problems/combination-sum/description/
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
class Solution { | |
public List<List<Integer>> combinationSum(int[] candidates, int target) { | |
if (candidates == null || candidates.length == 0) { | |
return new LinkedList<List<Integer>>(); | |
} | |
List<List<Integer>> results = new LinkedList<>(); | |
List<Integer> prefix = new LinkedList<>(); | |
recurseSum(results, prefix, 0, candidates, target); | |
return results; | |
} | |
private void recurseSum(List<List<Integer>> results, List<Integer> prefix, int start, final int[] candidates, int target) { | |
// Stopping condition | |
if (target == 0) { | |
results.add(new LinkedList<Integer>(prefix)); | |
} | |
for (int i = start; i < candidates.length; i++) { | |
int cur = candidates[i]; | |
if (cur > target) { | |
continue; | |
} | |
int diff = target - cur; | |
if (diff < 0) { | |
continue; | |
} | |
prefix.add(cur); | |
recurseSum(results, prefix, i, candidates, diff); | |
prefix.remove(prefix.size() - 1); | |
} | |
} | |
} |
Author
hsaputra
commented
Oct 10, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment