gpt4 book ai didi

java - 使用递归查找系列

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:40 28 4
gpt4 key购买 nike

如果 n 为 3,我正在尝试使用递归打印 122333221。但是我无法解决它。我们已经给出了我们必须使用递归打印系列的数字。例如,如果 n = 3,那么它应该打印 122333221 .

public static void print(int n){
if(n < 1 ){
return;
}

print(n-1);
for(int i = 1; i <= n; i++){
System.out.print(n);
}

}

public static void main(String[] args) {
print(3);

}

最佳答案

您必须使用通过参数跟踪状态的常规技术,方法是定义一个 public 方法,该方法使用带有额外参数的 private 方法。

// Repeats n n times.
private static void repeat(int n) {
for (int i = 0; i < n; i++) {
System.out.print(n);
}
}

private static void print(int n, int v) {
if (n == v) {
// Just once for the deepest level.
repeat(n);
} else {
// Wrap the inner print ...
repeat(n);
// Recurse with the next higher value.
print(n + 1, v);
// ... end the wrap.
repeat(n);
}
}

public static void print(int n) {
System.out.print(n+": ");
print(1, n);
System.out.println();
}

public void test(String[] args) {
for (int i = 1; i <= 9 ; i++) {
print(i);
}
}

关于java - 使用递归查找系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48208061/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com