代码随想录算法训练营第44天|完全背包, 518. 零钱兑换 II,377. 组合总和 Ⅳ

完全背包

void test_CompletePack() {
    vector weight = {1, 3, 4};
    vector value = {15, 20, 30};
    int bagWeight = 4;

    vector dp(bagWeight + 1, 0);

    for(int j = 0; j <= bagWeight; j++) { 
        for(int i = 0; i < weight.size(); i++) { 
            if (j - weight[i] >= 0) dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
        }
    }
    cout << dp[bagWeight] << endl;
}
int main() {
    test_CompletePack();
}

518. 零钱兑换 II

class Solution {
public:
    int change(int amount, vector& coins) {
        vector dp(amount + 1);
        dp[0] = 1;
        for (int& coin : coins) {
            for (int i = coin; i <= amount; i++) {
                dp[i] += dp[i - coin];
            }
        }
        return dp[amount];
    }
};

377. 组合总和 Ⅳ

class Solution {
public:
    int combinationSum4(vector& nums, int target) {
        vector dp(target + 1);
        dp[0] = 1;
        for (int i = 1; i <= target; i++) {
            for (int& num : nums) {
                if (num <= i && dp[i - num] < INT_MAX - dp[i]) {
                    dp[i] += dp[i - num];
                }
            }
        }
        return dp[target];
    }
};

你可能感兴趣的:(c++)