Day39 动态规划-多重背包 && 完全背包3

Day39 动态规划-多重背包 && 完全背包3_第1张图片

#include 
#include 
using namespace std;

int C, n;

int main() {
    cin >> C >> n;
    vector weight(n, 0);
    vector price(n, 0);
    vector nums(n, 0);
    for(int i = 0; i < n; i++){
        cin >> weight[i];
    }
    for(int i = 0; i < n; i++){
        cin >> price[i];
    }
    for(int i = 0; i < n; i++){
        cin >> nums[i];
    }
    
    vector dp(C + 1, 0);
    
    for(int i = 0; i < n; i++){
        //遍历物品
        for(int j = C; j >= weight[i]; j--){
            //遍历背包
            for(int k = 1; k <= nums[i] && j - k * weight[i] >= 0; k++){
                //遍历个数
                dp[j] = max(dp[j], dp[j - k * weight[i]] + k * price[i]);
            }
        }
    }
    
    cout << dp[C] << endl;

    return 0;
}

LeetCode 139. 单词拆分

class Solution {
public:
    bool wordBreak(string s, vector& wordDict) {
        unordered_set set(wordDict.begin(), wordDict.end());
        vector dp(s.size() + 1, false);
        dp[0] = true;

        for(int j = 1; j <= s.size(); j++){
            //遍历背包
            for(int i = 0; i < j; i++){
                //遍历物品
                string word = s.substr(i, j - i);
                if(dp[i] && set.count(word)){
                    dp[j] = true;
                }
            }
        }
        return dp[s.size()];
    }
};

你可能感兴趣的:(算法学习,动态规划,算法)