Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

01背包问题的代码问题 #2523

Open
AndrewLawrence80 opened this issue Apr 11, 2024 · 0 comments
Open

01背包问题的代码问题 #2523

AndrewLawrence80 opened this issue Apr 11, 2024 · 0 comments

Comments

@AndrewLawrence80
Copy link

如果迭代物品下标从1开始,代码应该是

vector<vector<int>> dp(weight.size()+1, vector<int>(bagweight + 1, 0));
for(int i = 1; i < weight.size(); i++) { // 遍历物品
    for(int j = 0; j <= bagweight; j++) { // 遍历背包容量
        if (j < weight[i-1]) dp[i][j] = dp[i - 1][j]; // i-1的作用是确保第一个物品(下标为0)会被访问到
        else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i-1]] + value[i-1]);
    }
}
cout << dp[weight.size()][bagweight] << endl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant