diff --git a/Java/Combination_sum.java b/Java/Combination_sum.java new file mode 100644 index 00000000..7a4152a9 --- /dev/null +++ b/Java/Combination_sum.java @@ -0,0 +1,20 @@ +//Beats 99.91% of the solutions + +public List> combinationSum(int[] candidates, int target) { + List> solutions = new ArrayList<>(); + List solution = new ArrayList<>(); + solve(solutions, solution, candidates, target, 0); + return solutions; +} +private static void solve(List> solutions, List solution, int[] candidates, int target, int start){ + if(target == 0) { + solutions.add(new ArrayList<>(solution)); + } + for(int i = start; i < candidates.length; i++){ + if(candidates[i] <= target){ + solution.add(candidates[i]); + solve(solutions, solution, candidates, target - candidates[i], i); + solution.remove(solution.size() - 1); + } + } +}