-
-
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.
This file contains 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
// 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); | |
} | |
} | |
} |
Author
anil477
commented
Sep 7, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment