[LeetCode][377. Combination Sum IV] 2 Approaches: Backtrack and DP with Follow Up Analysis
By Long Luo
This article is the solution 2 Approaches: Backtrack and DP with Follow Up Analysis of Problem 377. Combination Sum IV .
Here shows 2 Approaches to slove this problem: Backtrack and Dynamic Programming.
Backtrack
The Backtrack will be a complete search and its time complexity will be \(O(2^n)\).
Surely it will be TLE!1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Solution {
int total = 0;
public int combinationSum4(int[] nums, int target) {
total = 0;
Arrays.sort(nums);
backtrack(nums, target);
return total;
}
private void backtrack(int[] nums, int remain) {
if (remain == 0) {
total++;
return;
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > remain) {
break;
}
backtrack(nums, remain - nums[i]);
}
}
}
Analysis
- Time Complexity: \(O(2^n)\)
- Space Complexity: \(O(\textit{target})\)