Skip to content

Instantly share code, notes, and snippets.

@Buzz-Lightyear
Created October 6, 2015 01:47
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 Buzz-Lightyear/85aab6e372423d025e91 to your computer and use it in GitHub Desktop.
Save Buzz-Lightyear/85aab6e372423d025e91 to your computer and use it in GitHub Desktop.
public class Solution
{
public List<List<Integer>> combinationSum(int[] candidates, int target)
{
List<List<Integer>> sumCombinations = new ArrayList<>();
if(candidates == null || candidates.length == 0)
return sumCombinations;
if((candidates.length == 1) && (target % candidates[0] == 0))
{
List<Integer> result = new ArrayList<>();
for(int i = 0; i < target / candidates[0]; i++)
result.add(candidates[0]);
sumCombinations.add(result);
return sumCombinations;
}
computeAllCombinationSums(candidates, target, sumCombinations, 0, 0, new ArrayList<Integer>());
return sumCombinations;
}
private void removeLastElement(List<Integer> list)
{
list.remove(list.size() - 1);
}
private void computeAllCombinationSums(int[] candidates, int target, List<List<Integer>> result, int start, int sum, List<Integer> currentList)
{
if(sum > target)
return;
for(int i = start; i < candidates.length; i++)
{
sum += candidates[i];
currentList.add(candidates[i]);
if(sum == target)
{
result.add(new ArrayList<Integer>(currentList));
removeLastElement(currentList);
return;
}
if(sum < target)
computeAllCombinationSums(candidates, target, result, i, sum, currentList);
sum -= candidates[i];
removeLastElement(currentList);
}
}
}
@aoben10
Copy link

aoben10 commented Jun 14, 2016

Why do we use depth first search here? As in when I read this problem, how would i know DFS is the way to approach it?

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