Description Link to heading

377.combination-sum-iv

Solution Link to heading

This problem is still a unbounded-knapsack-problem, however, what this problem want to get is permutations rather than combinations.

With reference to 518.coin-change-ii, traverse volume first, than traverse items.

代码 Link to heading

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int>dp (target + 1, 0);
        dp[0] = 1;	
        for (int j = 0; j <= target; j++) {
            for (int i = 0; i < nums.size(); i++) {
                // prevent overflow, not dp[j] + dp[j - nums[i]] < INT_MAX
                if (j >= nums[i] && dp[j] < INT_MAX - dp[j - nums[i]])
                    dp[j] += dp[j - nums[i]];
            }
        }
        return dp[target];
    }
};