有人可以解释这行代码何时结束? :
void constituteSubsequence(int i){
if( Pred[i] + 1) constituteSubsequence(Pred[i]);
cout << a[i] << " ";
}
在这个计算最长增长子序列的程序中:
#include <iostream>
using namespace std;
int Pred[1000]; //Pred is previous.
int a[1000], v[1000], n, imax;
void read() {
cout << " n = ";
cin >> n;
cout << " Sequence: ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
}
void constituteSubsequence(int i) {
if (Pred[i] + 1) constituteSubsequence(Pred[i]);
cout << a[i] << " ";
}
void calculate() {
int i, j;
v[0] = 1;
imax = 0;
Pred[0] = -1;
for (int i = 1; i < n; i++) {
v[i] = 1;
Pred[i] = -1;
for (int j = 0; j < i; j++) {
if (a[j] < a[i] && v[j] + 1 > v[i]) {
v[i] = v[j] + 1;
Pred[i] = j;
}
if (v[i] > v[imax]) {
imax = i;
}
}
}
}
void write() {
cout << " Longest Increasing Subsequence : ";
constituteSubsequence(imax);
cout << endl << " Length: " << v[imax];
}
int main() {
read();
calculate();
write();
return 0;
}
如果我运行此代码,它会按预期编译并运行,但是在找到0值(false)并且打印cout&lt;&lt;之后,该条件如何重复? a [i]?什么时候停止?
答案 0 :(得分:2)
在C ++中,整数表达式可以视为布尔值。例如,在if
语句Pred[i] + 1
的上下文中表示(Pred[i] + 1) != 0
这为您的问题提供了答案:递归调用链将在Pred[i]
为-1
时结束。当然,表达相同条件的更容易阅读的方式是使用!=
运算符:
if( Pred[i] != -1) {
constituteSubsequence(Pred[i]);
}