代码随想录算法训练营第四十六天| LeetCode70. 爬楼梯 322. 零钱兑换 79.完全平方数

139.单词拆分

题目:

class Solution {
public:
    bool wordBreak(string s, vector& wordDict) {
        unordered_set wordSet(wordDict.begin(),wordDict.end());
        vector dp(s.size()+1,false);
        dp[0] = true;
        for(int i = 1; i <= s.size(); ++i){
            for(int j = 0; j < i; ++j){
                string underword = s.substr(j,i-j);
                if(wordSet.find(underword) != wordSet.end() && dp[j]){
                    dp[i] =  true;
                }
            }
            
        }
        return dp[s.size()];
    }
};

多重背包

void test_multi_pack() {
    vector weight = {1, 3, 4};
    vector value = {15, 20, 30};
    vector nums = {2, 3, 2};
    int bagWeight = 10;
    vector dp(bagWeight + 1, 0);


    for(int i = 0; i < weight.size(); i++) { // 遍历物品
        for(int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量
            // 以上为01背包,然后加一个遍历个数
            for (int k = 1; k <= nums[i] && (j - k * weight[i]) >= 0; k++) { // 遍历个数
                dp[j] = max(dp[j], dp[j - k * weight[i]] + k * value[i]);
            }
        }
        // 打印一下dp数组
        for (int j = 0; j <= bagWeight; j++) {
            cout << dp[j] << " ";
        }
        cout << endl;
    }
    cout << dp[bagWeight] << endl;
}
int main() {
    test_multi_pack();
}

背包问题总结

最关键的两步:递推公式和遍历顺序,

问能否能装满背包(或者最多装多少):dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]); 

问装满背包有几种方法:dp[j] += dp[j - nums[i]] 

问背包装满最大价值:dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); 

问装满背包所有物品的最小个数:dp[j] = min(dp[j - coins[i]] + 1, dp[j]);

如果求组合数就是外层for循环遍历物品,内层for遍历背包

如果求排列数就是外层for遍历背包,内层for循环遍历物品

你可能感兴趣的:(代码随想录算法训练营,算法,leetcode,动态规划)