Skip to content

Commit bdabf74

Browse files
committed
Passed only small judge.
1 parent a0ff320 commit bdabf74

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

CombinationSum.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class Solution {
2+
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
3+
// Start typing your Java solution below
4+
// DO NOT write main() function
5+
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
6+
Stack<Integer> stack = new Stack<Integer>();
7+
Arrays.sort(candidates);
8+
combinationHelper(candidates, stack, result, target);
9+
return result;
10+
}
11+
12+
public void combinationHelper(int[] candidates, Stack<Integer> stack, ArrayList<ArrayList<Integer>> result, int target){
13+
if (target <= 0){
14+
if (target == 0){
15+
ArrayList<Integer> temp = new ArrayList<Integer>(stack);
16+
Collections.sort(temp);
17+
if (!result.contains(temp)){
18+
result.add(temp);
19+
}
20+
}
21+
return;
22+
}
23+
for (int i = 0; i < candidates.length; i ++){
24+
stack.push(candidates[i]);
25+
combinationHelper(candidates, stack, result, target - candidates[i]);
26+
stack.pop();
27+
}
28+
}
29+
}

CombinationSum2.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public class Solution {
2+
public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {
3+
// Start typing your Java solution below
4+
// DO NOT write main() function
5+
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
6+
Stack<Integer> stack = new Stack<Integer>();
7+
Arrays.sort(candidates);
8+
combinationHelper(candidates, stack, result, target, 0);
9+
return result;
10+
}
11+
12+
public void combinationHelper(int[] candidates, Stack<Integer> stack, ArrayList<ArrayList<Integer>> result, int target, int start){
13+
if (target <= 0){
14+
if (target == 0){
15+
ArrayList<Integer> temp = new ArrayList<Integer>(stack);
16+
Collections.sort(temp);
17+
if (!result.contains(temp)){
18+
result.add(temp);
19+
}
20+
}
21+
return;
22+
}
23+
if (start == candidates.length) return;
24+
for (int i = start; i < candidates.length; i ++){
25+
stack.push(candidates[i]);
26+
combinationHelper(candidates, stack, result, target - candidates[i], ++start);
27+
stack.pop();
28+
}
29+
30+
}
31+
}

0 commit comments

Comments
 (0)