Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active September 7, 2019 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/5fc6587eeb3deb4dfe65a093193bf163 to your computer and use it in GitHub Desktop.
Save anil477/5fc6587eeb3deb4dfe65a093193bf163 to your computer and use it in GitHub Desktop.
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
// https://www.interviewbit.com/problems/combination-sum/
// http://www.goodtecher.com/leetcode-39-combination-sum/
// https://www.youtube.com/watch?v=irFtGMLbf-s
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Solution {
public static void main(String[] args) {
Solution x = new Solution();
int[] input = new int[]{2,3,6,7};
x.combinationSum(input, 7);
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (candidates == null || candidates.length == 0) {
return results;
}
Arrays.sort(candidates);
List<Integer> combination = new ArrayList<Integer>();
toFindCombinationsToTarget(results, combination, candidates, target, 0);
System.out.println(results);
return results;
}
private void toFindCombinationsToTarget(List<List<Integer>> results, List<Integer> combination, int[] candidates, int target, int startIndex) {
if (target == 0) {
results.add(new ArrayList<Integer>(combination));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
if (candidates[i] > target) {
break;
}
combination.add(candidates[i]);
toFindCombinationsToTarget(results, combination, candidates, target - candidates[i], i);
combination.remove(combination.size() - 1);
}
}
}
@anil477
Copy link
Author

anil477 commented Sep 7, 2019

Screen Shot 2019-09-07 at 9 36 08 PM

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