-
Notifications
You must be signed in to change notification settings - Fork 72
/
Solution.java
34 lines (30 loc) · 1.25 KB
/
Solution.java
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
31
32
33
34
package g0001_0100.s0039_combination_sum;
// #Medium #Top_100_Liked_Questions #Array #Backtracking #Algorithm_II_Day_10_Recursion_Backtracking
// #Level_2_Day_20_Brute_Force/Backtracking #Udemy_Backtracking/Recursion
// #Big_O_Time_O(2^n)_Space_O(n+2^n) #2024_11_10_Time_1_ms_(99.99%)_Space_44.5_MB_(51.73%)
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<Integer>> combinationSum(int[] coins, int amount) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> subList = new ArrayList<>();
combinationSumRec(coins.length, coins, amount, subList, ans);
return ans;
}
private void combinationSumRec(
int n, int[] coins, int amount, List<Integer> subList, List<List<Integer>> ans) {
if (amount == 0 || n == 0) {
if (amount == 0) {
List<Integer> base = new ArrayList<>(subList);
ans.add(base);
}
return;
}
if (amount - coins[n - 1] >= 0) {
subList.add(coins[n - 1]);
combinationSumRec(n, coins, amount - coins[n - 1], subList, ans);
subList.remove(subList.size() - 1);
}
combinationSumRec(n - 1, coins, amount, subList, ans);
}
}