【LeetCode】377. Combination Sum IV
阿新 • • 發佈:2019-02-18
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.
題解:通過陣列中的元素進行組合,滿足和等於target。每個元素可以重複利用。
- 解法一:動態規劃(自下而上):
該題跟上臺階有點類似,我們需要維護一個dp陣列,dp[i]代表和為i在nums中得到的結果數,對每個i我們需要遍歷陣列nums,
當i >= num[x] 時,dp[i]+=dp[i-x]
.
以nums=[1,2,3] target =4 為例:
3 = 1+x => x = 2
3 = 2+x => x = 1
3 = 3+x => x = 0
即 dp[3] = dp[2]+dp[1]+dp[0]
- 程式碼
public static int method(int[] nums,int target){
int[] dp = new int[target+1];
dp[0] = 1;
for(int i = 1;i<=target ; i++){
for (int num:nums){
if(i >=num) dp[i] +=dp[i-num];
}
}
return dp[target];
}
- 解法二:使用遞迴加map(自上而下):
該方法是使用map加上遞迴的方式解決,利用Map儲存每個target的結果集。
遍歷nums,
當target<
nums[i]時,target=target-nums[i];將更新後的target以及target對應的解集存入map。
- 程式碼
static Map<Integer,Integer> map = new HashMap<>();
public static int combinationSum4(int[] nums, int target) {
int count = 0;
if(nums == null || nums.length == 0 || target < 0) return 0;
if(target == 0) return 1;
if(map.containsKey(target)) return map.get(target);
for(int num : nums){
count += combinationSum4(nums,target-num);
}
map.put(target,count);
return count;
}