01背包问题

最原始的01背包问题:

Solution01: 自顶向下,记忆化搜索

class Knapsack01{
private:
    vector<vector<int>> memo;

    int bestValue(const vector<int> &w, const vector<int> &v, int index, int c){

        if ( index < 0 || c <= 0 )
            return 0;

        if ( memo[index][c] != -1)
            return memo[index][c];

        int res = bestValue(w, v, index-1, c);
        if( c >= w[index] )
            res = max(res, v[index] + bestValue(w, v, index-1, c-w[index]));
        memo[index][c] = res;
        return res;

    }
public:
    int knapsack01(const vector<int> &w, const vector<int> &v, int C){

        int n = w.size();
        memo = vector<vector<int>>(n, vector<int>(C+1, -1));
        return bestValue(w, v, n-1, C);

    }
};

Solution02: 自底向上 动态规划

class Knapsack01{
public:
    int knapsack01(const vector<int> &w, const vector<int> &v, int C){

       assert( w.size() == v.size() );
       int n = w.size();
       if ( n==0 )
           return 0;

       vector<vector<int>> memo(n, vector<int>(C+1, -1));

       for ( int j = 0; j <= C; j++ ){
           memo[0][j] = ( j >= w[0] ? v[0] : 0);
       }

        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= C ; j++) {
                memo[i][j] = memo[i-1][j];
                if ( j >= w[i] )
                    memo[i][j] = max( memo[i][j], v[i] + memo[i-1][j-w[i]]);
            }
        }

        return memo[n-1][C];
    }
};

总结: 定义状态和状态转移
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值