Skip to content

Instantly share code, notes, and snippets.

@anil477
Created February 16, 2021 12:47
Show Gist options
  • Save anil477/012bced56d35d7cd048452d3322cfb5a to your computer and use it in GitHub Desktop.
Save anil477/012bced56d35d7cd048452d3322cfb5a to your computer and use it in GitHub Desktop.
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
// https://leetcode.com/problems/combination-sum/
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<List<Integer>>();
getResult(result, new ArrayList<Integer>(), candidates, target, 0);
return result;
}
private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start) {
// System.out.println(cur);
if (target > 0) {
for (int i = start; i < candidates.length && candidates[i] <= target; i++) {
cur.add(candidates[i]);
getResult(result, cur, candidates, target - candidates[i], i);
cur.remove(cur.size() - 1);
}
} else if(target == 0 ){
result.add(new ArrayList<Integer>(cur));
}
}
}
@anil477
Copy link
Author

anil477 commented Feb 16, 2021

Screen Shot 2021-02-16 at 6 14 00 PM

Screen Shot 2021-02-16 at 6 14 12 PM

Screen Shot 2021-02-16 at 6 14 20 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment