ID | Title | Difficulty | |
---|---|---|---|
Loading... |
377. Combination Sum IV
Medium
LeetCode
Array, Dynamic Programming
Problem
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Code
class Solution {
public int combinationSum4(int[] nums, int target) {
if(nums == null || nums.length == 0) return 0;
int[] res = new int[target + 1];
res[0] = 1;
for(int i = 1; i < res.length; i++){
for(int num : nums){
if(i - num >= 0){
res[i] += res[i - num];
}
}
}
return res[target];
}
}
class Solution {
public int combinationSum4(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
Arrays.sort(nums);
return helper(nums, target, map);
}
private int helper(int[] nums, int target, HashMap<Integer, Integer> map) {
if (map.containsKey(target)) return map.get(target);
if(target < 0) return 0;
if(target == 0) return 1;
int res = 0;
for(int i = 0; i < nums.length; i++) {
if(target - nums[i] >= 0) {
res += helper(nums, target - nums[i], map);
}
}
map.put(target, res);
return res;
}
}
按 <- 键看上一题!
376. Wiggle Subsequence
按 -> 键看下一题!
378. Kth Smallest Element in a Sorted Matrix