875899. Combination Sum IV
Medium
4-Combination-Sum
Summary
Given an array of distinct integers and a target sum, find the number of combinations that add up to the target sum. The same element can be used multiple times.
This problem is about dynamic programming and arrays, requiring an optimization approach to solve.
Detailed Explanation
The key idea is to use dynamic programming to build up solutions for smaller sums, then combine them to find the solution for the given target sum. Here's a step-by-step breakdown:
- Initialize a 2D array
dpwith dimensions(target_sum + 1) x (array_size + 1)filled with zeros. - Iterate through each element in the input array:
- For each element, iterate from
target_sumdown to its value:- If the current sum is equal to the target sum, increment the count of combinations that add up to the target sum.
- Update the
dptable by adding the number of combinations for the current sum minus the current element's value (if it exists) to the number of combinations for the current sum.
- For each element, iterate from
- The final answer is stored in the last row of the
dptable.
Here's an ASCII art diagram representing the dynamic programming table:
+--------+--------+--------+...+
| 0 | 1 | 2 |...|
+--------+--------+--------+...+
| 0, 1 | x, 1 | x, 2 |...|
| | | |
| ... | ... | ... |...
| target_sum | | |
+--------+--------+--------+...+
The time complexity is O(n * t), where n is the size of the input array and t is the target sum. The space complexity is O(t).
Optimized Solutions
Java
public int combinationSum4(int[] nums, int target) {
int[][] dp = new int[target + 1][nums.length + 1];
for (int i = 0; i <= target; i++) {
dp[i][0] = 0;
}
for (int i = 0; i <= target; i++) {
for (int j = 0; j < nums.length; j++) {
if (i >= nums[j]) {
dp[i][j + 1] = dp[i - nums[j]][j] + dp[i][j];
} else {
dp[i][j + 1] = dp[i][j];
}
}
}
return dp[target][nums.length];
}