java - 使用递归查找系列

标签 java recursion

如果 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/

相关文章:

java - 嵌套类可以实例化外部类吗?

c# - 递归到动态函数

java - NgWebDriver 仅在重新加载页面后才工作。为什么?

java - 不使用递归遍历目录?

java - log4j2 - 未解析的符号调试

java - 设置日期和时间格式

arrays - 使用递归查找数组中的最大元素

c# - 通过递归遍历所有属性的属性来比较两个对象?

java - 如何检查用户是否是 Telegram 群组的成员?

java - Open Liberty 中的 Servlet 编码问题