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:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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. | 
题目大意:给你一些数和一个目标值,问使用这些数(每个数可以被使用任意次数)加起来等于目标值的组合(其实是不重复的排列)有多少种。
Idea:
DP

Solution:
C++ / Recursion + Memorization
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Author: Huahua // Runtime: 0 ms class Solution { public:     int combinationSum4(vector<int>& nums, int target) {         m_ = vector<int>(target + 1, -1);         m_[0] = 1;         return dp(nums, target);     }     private:     int dp(const vector<int>& nums, int target) {         if (target < 0) return 0;         if (m_[target] != -1) return m_[target];         int ans = 0;         for (const int num : nums)             ans += dp(nums, target - num);         return m_[target] = ans;     }     vector<int> m_; }; | 
C++ / DP
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Author: Huahua // Runtime: 3 ms class Solution { public:     int combinationSum4(vector<int>& nums, int target) {         vector<int> dp(target + 1, 0); // dp[i] # of combinations sum up to i         dp[0] = 1;         for (int i = 1; i <= target; ++i)             for (const int num : nums)                 if (i - num >= 0)                     dp[i] += dp[i - num];                    return dp[target];     } }; | 
Related Problems:
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.


 
  
Be First to Comment