【LeetCode】377. Combination Sum IV 組合總和 Ⅳ(Medium)(JAVA)
阿新 • • 發佈:2020-12-31
技術標籤:Leetcodeleetcodejava演算法面試資料結構
【LeetCode】377. Combination Sum IV 組合總和 Ⅳ(Medium)(JAVA)
題目地址: https://leetcode.com/problems/combination-sum-iv/
題目描述:
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.
Follow up:
What if negative numbers are allowed in the given array?
What limitation we need to add to the question to allow negative numbers?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
題目大意
給定一個由正整陣列成且不存在重複數字的陣列,找出和為給定目標正整數的組合的個數。
進階:
如果給定的陣列中含有負數會怎麼樣?
問題會產生什麼變化?
我們需要在題目中新增什麼限制來允許負數的出現?
解題方法
- 這一題和 coins 那題比較類似,給一些領錢,看有多少種兌換方式
- 採用動態規劃,函式 dp[i] 表示,和為 i 的話有多少總演算法
- 如何計算 dp[i]? 可以遍歷 nums 陣列,加上 dp[i - nums[j]] 的演算法也就是: dp[i] += dp[i - nums[j]]
class Solution {
public int combinationSum4(int[] nums, int target) {
Arrays.sort(nums);
int[] dp = new int[target + 1];
dp[0] = 1;
for (int i = 1; i <= target; i++) {
for (int j = 0; j < nums.length && nums[j] <= i; j++) {
dp[i] += dp[i - nums[j]];
}
}
return dp[target];
}
}
執行耗時:2 ms,擊敗了36.87% 的Java使用者
記憶體消耗:35.6 MB,擊敗了88.05% 的Java使用者