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?
How does it change the problem?
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.
這道題是組合之和系列的第四道,博主開始想當然的以為還是用遞歸來解,結果寫出來發現 TLE 了,的確 OJ 給了一個 test case 為 [4,1,2] 32,這個結果是 39882198,用遞歸需要好幾秒的運算時間,實在是不高效,估計這也是為啥只讓返回一個總和,而不是返回所有情況,不然機子就爆了。而這道題的真正解法應該是用 DP 來做,解題思想有點像之前爬梯子的那道題 Climbing Stairs,這里需要一個一維數組 dp,其中 dp[i] 表示目標數為i的解的個數,然后從1遍歷到 target,對於每一個數i,遍歷 nums 數組,如果 i>=x, dp[i] += dp[i - x]。這個也很好理解,比如說對於 [1,2,3] 4,這個例子,當計算 dp[3] 的時候,3可以拆分為 1+x,而x即為 dp[2],3也可以拆分為 2+x,此時x為 dp[1],3同樣可以拆為 3+x,此時x為 dp[0],把所有的情況加起來就是組成3的所有情況了,參見代碼如下:
解法一:
class Solution { public: int combinationSum4(vector<int>& nums, int target) { vector<int> dp(target + 1); dp[0] = 1; for (int i = 1; i <= target; ++i) { for (auto a : nums) { if (i >= a) dp[i] += dp[i - a]; } } return dp.back(); } };
如果 target 遠大於 nums 數組的個數的話,上面的算法可以做適當的優化,先給 nums 數組排個序,然后從1遍歷到 target,對於i小於數組中的數字x時,直接 break 掉,因為后面的數更大,其余地方不變,參見代碼如下:
解法二:
class Solution { public: int combinationSum4(vector<int>& nums, int target) { vector<int> dp(target + 1); dp[0] = 1; sort(nums.begin(), nums.end()); for (int i = 1; i <= target; ++i) { for (auto a : nums) { if (i < a) break; dp[i] += dp[i - a]; } } return dp.back(); } };
我們也可以使用遞歸+記憶數組的形式,不過這里的記憶數組用的是一個 HashMap。在遞歸函數中,首先判斷若 target 小於0,直接返回0,若 target 等於0,則返回1。若當前 target 已經在 memo 中存在了,直接返回 memo 中的值。然后遍歷 nums 中的所有數字,對每個數字都調用遞歸,不過此時的 target 要換成 target-nums[i],然后將返回值累加到結果 res 中即可,參見代碼如下:
解法三:
class Solution { public: int combinationSum4(vector<int>& nums, int target) { unordered_map<int, int> memo; return helper(nums, target, memo); } int helper(vector<int>& nums, int target, unordered_map<int, int>& memo) { if (target < 0) return 0; if (target == 0) return 1; if (memo.count(target)) return memo[target]; int res = 0, n = nums.size(); for (int i = 0; i < n; ++i) { res += helper(nums, target - nums[i], memo); } return memo[target] = res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/377
類似題目:
參考資料:
https://leetcode.com/problems/combination-sum-iv/
https://leetcode.com/problems/combination-sum-iv/discuss/85079/My-3ms-Java-DP-solution