Open yokostan opened 5 years ago
Bottom-up DP:
class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int [target + 1];
dp[0] = 1;
int n = nums.length;
for (int i = 1; i <= target; i++) {
for (int j = 0; j < n; j++) {
if (i - nums[j] >= 0) {
dp[i] = dp[i] + dp[i - nums[j]];
}
}
}
return dp[target];
}
}
The 'intuitive' solution:
But will get TLE in leetcode.
If we use dp to store how many combinations we can get for each target number, then our runtime can beat 100%: