-
-
Save anil477/d21b1d57d51c47d972600e29bed47e00 to your computer and use it in GitHub Desktop.
Combination Sum II
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-ii/ | |
import java.util.*; | |
public class Solution { | |
public static void main(String[] args) { | |
Solution x = new Solution(); | |
int[] input = new int[]{10,1,2,7,6,1,5}; | |
x.combinationSum(input, 8); | |
} | |
public Set<List<Integer>> combinationSum(int[] candidates, int target) { | |
Set<List<Integer>> results = new HashSet<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(Set<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+1); | |
combination.remove(combination.size() - 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment