用递归反向打印字符串,n 为字符在整个字符串 str 中的索引位置
打印函数在递归函数前面为正序,在递归函数后面会变为倒叙(以本题为例)
- 递:n 从 0 开始,每次 n + 1,一直递到 n == str.length() - 1
- 归:从 n == str.length() 开始归,从归打印,自然是逆序的
递推关系
f
(
n
)
=
{
停止
n
=
s
t
r
.
l
e
n
g
t
h
(
)
f
(
n
+
1
)
0
≤
n
≤
s
t
r
.
l
e
n
g
t
h
(
)
−
1
f(n) = \begin{cases} 停止 & n = str.length() \\ f(n+1) & 0 \leq n \leq str.length() - 1 \end{cases}
f(n)={停止f(n+1)n=str.length()0≤n≤str.length()−1
代码为:
package com.itheima.algorithm.recursion;
//反向打印字符串
public class ReversePrintString {
public static void f(int n, String str) {
if (n == str.length()) return;
f(n + 1, str);
System.out.println(str.charAt(n));
}
public static void main(String[] args) {
f(0, "abcd");
}
}
同理:也可以从0到n来递归,将打印放在递归函数前面即可;
在递归函数中每次递归都会进入下一个递归函数,如果将其他的逻辑写在递归函数后面会导致先一直进入到递归函数中一个子集得出结果后,在继续返回到上一个递归函数执行未执行的命令,一直归到最外层结束;
例子上面的递归函数拆解开来,一些不会执行的语句我们就省略了,例如除了最里层的if语句,这里是倒叙打印abc字符串(伪代码):
void reversePrint(String str, int index = 0) {
void reversePrint(String str, int index = 1) {
void reversePrint(String str, int index = 2) {
void reversePrint(String str, int index = 3) {
if (index == str.length()) {
return; // 开始归
}
}
System.out.println(str.charAt(index)); // 打印 c
}
System.out.println(str.charAt(index)); // 打印 b
}
System.out.println(str.charAt(index)); // 打印 a
}