#cspjc12. 递归1
递归1
递归1
1.(递归边界)
int func(int n) {
if (n == 0) return 1;
return func(n - 1) + 1;
}
调用 func(3) 的返回值是( )?{{ select(1) }}
- 5
- 2
- 3
- 4
2.(输出顺序)
void print(int n) {
if (n == 0) return;
cout << n;
print(n - 1);
}
调用 print(3) 的输出是( )?{{ select(2) }}
- 123
- 0123
- 321
- 3210
3.(返回值累加)
int sum(int n) {
if (n == 1) return 1;
return n + sum(n - 1);
}
调用 sum(4) 的结果是( )?{{ select(3) }}
- 15
- 10
- 6
- 4
4.(多路递归)
int f(int n) {
if (n <= 1) return 1;
return f(n - 1) + f(n - 2);
}
调用 f(3) 的结果是( )?{{ select(4) }}
- 4
- 5
- 2
- 3
5.(静态变量)
int count(int n) {
static int c = 0;
c++;
if (n == 0) return c;
return count(n - 1);
}
调用 count(2) 的返回值是( )?{{ select(5) }}
- 1
- 0
- 2
- 3
6.(递归后输出)
void rev(int n) {
if (n == 0) return;
rev(n - 1);
cout << n;
}
调用 rev(3) 的输出是( )?{{ select(6) }}
- 321
- 1230
- 123
- 0123 7.(边界条件影响)
int calc(int n) {
if (n < 0) return 0;
return n + calc(n - 2);
}
调用 calc(5) 的结果是( )?{{ select(7) }}
- 8
- 12
- 9
- 6
8.(递归与逻辑运算)
bool isEven(int n) {
if (n == 0) return true;
if (n == 1) return false;
return isEven(n - 2);
}
调用 isEven(5) 的结果是( )?{{ select(8) }}
- true
- 程序崩溃
- 不确定
- false
9.(递归调用顺序)
void seq(int n) {
if (n == 0) return;
cout << n % 2;
seq(n / 2);
}
调用 seq(6) 的输出是( )?{{ select(9) }}
- 110
- 101
- 011
- 010
10.(简单回溯——二进制串计数)
int ans = 0;
void dfs(int pos, int n) {
if (pos == n) {
ans++;
return;
}
for (int i = 0; i < 2; i++) { // 每位选0或1
dfs(pos + 1, n);
}
}
// 调用 dfs(0, 3);
调用后,全局变量 ans 的值是( )?{{ select(10) }}
- 6
- 8
- 4
- 2
11.(递归中使用全局变量)
int total = 0;
void accumulate(int n) {
if (n == 0) return;
total += n;
accumulate(n - 1);
}
// 调用 accumulate(4);
调用后,total 的值是( ){{ select(11) }}
- 4
- 6
- 10
- 0