Skip to content

Instantly share code, notes, and snippets.

@ShikaSD
Created January 10, 2020 17:47
Show Gist options
  • Save ShikaSD/9cf5fc8332d5efc5b937111e097ce56b to your computer and use it in GitHub Desktop.
Save ShikaSD/9cf5fc8332d5efc5b937111e097ce56b to your computer and use it in GitHub Desktop.
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<>();
findTarget(target, candidates.length - 1, new ArrayList<>(), result, candidates);
return result;
}
private void findTarget(int target, int lastElementIndex, List<Integer> current, List<List<Integer>> result, int[] candidates) {
if (target == 0) {
result.add(new ArrayList(current));
return;
}
for (int i = lastElementIndex; i >= 0; i--) {
int candidate = candidates[i];
if (target < candidate) {
continue;
}
current.add(candidates[i]);
findTarget(target - candidate, i, current, result, candidates);
current.remove(current.size() - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment