377. Combination Sum IV
Last updated
Last updated
/**
* Time complexity : O(T * N), T be the target value, and N be the
* number of elements in the input array.
* Space complexity : O(T)
*/
class Solution {
private HashMap<Integer, Integer> memo;
public int combinationSum4(int[] nums, int target) {
// minor optimization
// Arrays.sort(nums);
memo = new HashMap<>();
return combs(nums, target);
}
private int combs(int[] nums, int remain) {
if (remain == 0)
return 1;
if (memo.containsKey(remain))
return memo.get(remain);
int result = 0;
for (int num : nums) {
if (remain - num >= 0)
result += combs(nums, remain - num);
// minor optimizaton, early stopping
// else
// break;
}
memo.put(remain, result);
return result;
}
}/**
* Time complexity : O(T * N), T be the target value, and N be the
* number of elements in the input array.
* Space complexity : O(T)
*/
class Solution {
public int combinationSum4(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return 0;
}
int[] dp = new int[target+1];
dp[0] = 1;
for(int i = 0; i <= target; i++) {
for(int num: nums) {
if(i+num <= target) {
dp[i+num] += dp[i];
}
}
}
return dp[target];
}
}