这行如何递归返回数组的长度?
How is this line returning the length of the array in recursion?
我正在尝试使用调试器来理解这个递归并尝试逐步理解它 main.The 调试器显示 smallAns
returns 我可以的数组大小'不明白这个 smallAns 如何返回数组的大小 input[]
。谁能解释一下
#include<iostream>
using namespace std;
int subsequences(char input[], int startIndex,char output[][50]){
if(input[startIndex] == '[=10=]'){
output[0][0] = '[=10=]';
return 1;
}
int smallAns = subsequences(input, startIndex+1, output);
for(int i = smallAns; i < 2*smallAns; i++){
int row = i - smallAns;
output[i][0] = input[startIndex];
int j = 0;
for(; output[row][j] != '[=10=]'; j++){
output[i][j + 1] = output[row][j];
}
output[i][j + 1] = '[=10=]';
}
return 2*smallAns;
}
int main(){
char input[] = "abc";
char output[100][50];
int ans = subsequences(input, 0, output);
for(int i = 0; i < ans; i++){
for(int j = 0; output[i][j] != '[=10=]'; j++){
cout << output[i][j];
}
cout << endl;
}
}
算法的作用如下:
从末尾开始,子序列为空(或“\0”)。您有 1 个子序列。
看最后一个还没考虑的字符。对于您找到的所有子序列,您可以添加最后一个字符,也可以不添加。因此,您将子序列的数量增加了一倍。
重复。
因此,2 * smallAns 表示 "Take the number of subsequences found in the lower recursive call, and double it." 在您了解它的实现方式后,这就有意义了。因此注释和文档在代码中的重要性。 :)
我正在尝试使用调试器来理解这个递归并尝试逐步理解它 main.The 调试器显示 smallAns
returns 我可以的数组大小'不明白这个 smallAns 如何返回数组的大小 input[]
。谁能解释一下
#include<iostream>
using namespace std;
int subsequences(char input[], int startIndex,char output[][50]){
if(input[startIndex] == '[=10=]'){
output[0][0] = '[=10=]';
return 1;
}
int smallAns = subsequences(input, startIndex+1, output);
for(int i = smallAns; i < 2*smallAns; i++){
int row = i - smallAns;
output[i][0] = input[startIndex];
int j = 0;
for(; output[row][j] != '[=10=]'; j++){
output[i][j + 1] = output[row][j];
}
output[i][j + 1] = '[=10=]';
}
return 2*smallAns;
}
int main(){
char input[] = "abc";
char output[100][50];
int ans = subsequences(input, 0, output);
for(int i = 0; i < ans; i++){
for(int j = 0; output[i][j] != '[=10=]'; j++){
cout << output[i][j];
}
cout << endl;
}
}
算法的作用如下:
从末尾开始,子序列为空(或“\0”)。您有 1 个子序列。
看最后一个还没考虑的字符。对于您找到的所有子序列,您可以添加最后一个字符,也可以不添加。因此,您将子序列的数量增加了一倍。
重复。
因此,2 * smallAns 表示 "Take the number of subsequences found in the lower recursive call, and double it." 在您了解它的实现方式后,这就有意义了。因此注释和文档在代码中的重要性。 :)