Skip to content

Commit ab8aefc

Browse files
combination sum
1 parent a2088b5 commit ab8aefc

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

‎MEDIUM/src/medium/CombinationSum.java

+6-3
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,18 @@ public class CombinationSum {
99
public List<List<Integer>> combinationSum(int[] candidates, int target) {
1010
List<List<Integer>> result = new ArrayList();
1111
Arrays.sort(candidates);
12-
helper(candidates, target, 0, new ArrayList(), result);
12+
backtracking(candidates, target, 0, new ArrayList(), result);
1313
return result;
1414
}
1515

16-
private void helper(int[] candidates, int target, int startIndex, List<Integer> curr, List<List<Integer>> result){
16+
private void backtracking(int[] candidates, int target, int startIndex, List<Integer> curr, List<List<Integer>> result){
1717
if(target > 0){
18+
int prev = -1;
1819
for(int i = startIndex; i < candidates.length; i++){
20+
if (candidates[i] > target) return;//this is one very important step to optimize this algorithm: pruning
21+
if (prev != -1 && prev == candidates[i]) continue;
1922
curr.add(candidates[i]);
20-
helper(candidates, target-candidates[i], i, curr, result);
23+
backtracking(candidates, target-candidates[i], i, curr, result);
2124
curr.remove(curr.size()-1);
2225
}
2326
} else if(target == 0){

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@
119119
|56|[Merge Intervals](https://leetcode.com/problems/merge-intervals/)|[Solution](../../blob/master/HARD/src/hard/MergeIntervals.java)|O(n*logn)|O(1)|Hard|
120120
|47|[Permutations II](https://leetcode.com/problems/permutations-ii/)|[Solution](../../blob/master/MEDIUM/src/medium/PermutationsII.java)|O(n*n!)|O(n)|Medium|Backtracking
121121
|43|[Multiply Strings](https://leetcode.com/problems/multiply-strings/)|[Solution]|||Medium
122+
|39|[Combination Sum](https://leetcode.com/problems/combination-sum/)|[Solution](../../blob/master/MEDIUM/src/medium/CombinationSum.java)|O(k*n^k)|O(k)|Medium|Backtracking
122123
|31|[Next Permutation](https://leetcode.com/problems/next-permutation)|[Solution](../../blob/master/MEDIUM/src/medium/NextPermutation.java)|O(n)|O(1)|Medium|Array
123124
|24|[Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)|[Solution](../../blob/master/EASY/src/easy/SwapNodesinPairs.java)|O(n)|O(1)|Easy| Recursion, LinkedList
124125
|23|[Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)|[Solution](../../blob/master/HARD/src/hard/MergeKSortedList.java)|O(n*logk)|O(logk)|Hard|Heap

0 commit comments

Comments
 (0)