美文网首页
backpack1 i92

backpack1 i92

作者: Ariana不会哭 | 来源:发表于2019-02-12 08:04 被阅读0次
    图片.png 图片.png
    //i92
    //my
    class Solution {
    public:
    
        int backPack(int m, vector<int> &A) {
            int ss = A.size();
            if (ss == 0)
                return 0;
            vector<vector<int>> dp(ss + 1, vector<int>(m + 1, 0));
            for (int j = 1; j <= m; j++) {
                dp[0][j] = -1;
            }
    
            for (int i = 1; i <= ss; i++) {
                for (int j = 0; j <= m; j++) {
                    dp[i][j] = dp[i - 1][j];
                    if (j - A[i - 1] >= 0 && dp[i - 1][j - A[i - 1]] != -1) {
                        dp[i][j] = max(dp[i][j], dp[i - 1][j - A[i - 1]] + A[i - 1]);
                    }
                }
            }
    
            int ans = 0;
            for (int i = m; i >= 0; i--) {
                ans = max(ans, dp[ss][i]);
            }
            return ans;
        }
    };
    
    • 第二种方法:true or false 方法
    //my
    //f[i][w] = f[i-1][w] OR f[i-1][w-Ai-1]
    class Solution {
    public:
        int backPack(int m, vector<int> &A) {
            int ss = A.size();
            vector<vector<bool>> dp(ss + 1, vector<bool>(m + 1, false));
            dp[0][0] = true;
            for (int i = 1; i <= ss; i++) {
                for (int j = 0; j <= m; j++) {
                    dp[i][j] = dp[i - 1][j];
                    if (j - A[i - 1] >= 0 && dp[i - 1][j - A[i - 1]]) {
                        dp[i][j] = true;
                    }
                }
            }
    
            for (int w = m; w >= 0; w--) {
                if (dp[ss][w] == true)
                    return w;
            }
            return 0;
        }
    };
    

    相关文章

      网友评论

          本文标题:backpack1 i92

          本文链接:https://www.haomeiwen.com/subject/tahheqtx.html