在java中使用带限制的递归打印星星三角形

问题描述 投票:0回答:1

我们正在尝试使用java创建一个星形三角形,但限制是你不能使用任何循环、额外的方法、添加额外的参数、添加额外的变量,甚至不能使用字符串方法。解决方案似乎很简单,在到达基数后,您就从 n-1 开始新的递归,但问题是我们不允许使用额外的变量。有可能找到解决方案吗?如果没有,则在使用额外变量的限制中可能会出现错误,尽管仍应考虑其他变量。 基本代码在一行中打印 n 个星星,目标是使其创建一个三角形(无论是从 n 还是 1 开始,尽管两者都会受到赞赏)

n = 4 时的预期输出:

****
***
**
*

*
**
***
****

当前代码如下所示:

public class Test {

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

    public static void recurse(int x) {
        if (x == 0){
            System.out.println();
            return;
        }
        
        System.out.print("*");
        recurse(x-1);
    }
}
java recursion methods triangle
1个回答
0
投票

一种方法是使用

x
表示“打印
*
-x
次”,使用正
x
表示“打印大小为
x
的三角形”。

public static void recurse(int x) {
    if (x == 0){
        return; // base case for both negative and positive numbers
    }
    if (x < 0) { // we should print -x "*"s
        System.out.print("*");
        recurse(x + 1); // i.e. -(x - 1), one less "*"
        return;
    }
    // to reach this point, x must be positive

    // to print a triangle of size x...
    recurse(-x); // first print x stars...
    System.out.println(); // a new line...
    recurse(x - 1); // then print a smaller triangle
}
© www.soinside.com 2019 - 2024. All rights reserved.