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

章节 1.2 基本思路 有 Bug #6

Closed
XhstormR opened this issue Dec 1, 2017 · 2 comments
Closed

章节 1.2 基本思路 有 Bug #6

XhstormR opened this issue Dec 1, 2017 · 2 comments

Comments

@XhstormR
Copy link

XhstormR commented Dec 1, 2017

按文章所讲,写出的代码为

for (int i = 1; i <= N; i++) {
    for (int j = w[i - 1]; j <= W; j++) {
        F[i][j] = Math.max(F[i - 1][j - w[i - 1]] + v[i - 1], F[i - 1][j]);
    }
}

输出:

0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	
0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	100	100	100	100	100	100	100	100	100	100	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	
0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	220	

而正确代码应该为

for (int i = 1; i <= N; i++) {
    for (int j = 1; j <= W; j++) {
        if (w[i - 1] <= j) {
            F[i][j] = Math.max(F[i - 1][j - w[i - 1]] + v[i - 1], F[i - 1][j]);
        } else {
            F[i][j] = F[i - 1][j];
        }
    }
}

输出:

0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	60	
0	0	0	0	0	0	0	0	0	0	60	60	60	60	60	60	60	60	60	60	100	100	100	100	100	100	100	100	100	100	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	160	
0	0	0	0	0	0	0	0	0	0	60	60	60	60	60	60	60	60	60	60	100	100	100	100	100	100	100	100	100	100	160	160	160	160	160	160	160	160	160	160	180	180	180	180	180	180	180	180	180	180	220	
@zh-plus
Copy link

zh-plus commented May 29, 2018

不,原文的第二个循环是从V[i]开始,而不是你代码中所写的从W[i]开始。

@XhstormR
Copy link
Author

@zh-plus 我所说的问题跟 #4 是一样的,不过我用具体代码展示了出来。

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

2 participants