-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBacktracking.java
More file actions
30 lines (26 loc) · 1009 Bytes
/
Backtracking.java
File metadata and controls
30 lines (26 loc) · 1009 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.*;
public class Backtracking {
public List<List<Integer>> backtracking(int[] candidates, int target){
List<List<Integer>> result = new ArrayList<>();
backtrack(candidates, target, 0, new ArrayList<>(),result);
return result;
}
private void backtrack(int[] candidates, int target, int start, List<Integer> current, List<List<Integer>> result) {
if (target == 0) {
result.add(new ArrayList<>(current));
return;
}
if (target < 0) return;
for (int i = start; i < candidates.length; i++){
current.add(candidates[i]);
backtrack(candidates, target - candidates[i], i, current, result);
current.remove(current.size() - 1);
}
}
public static void main(String[] args){
Backtracking cs = new Backtracking();
int[] candidates = {2,3,6,7};
int target = 7;
System.out.println(cs.backtracking(candidates, target));
}
}