仅使用递归创建星形三角形

Ale*_*rge 9 java recursion

我需要编写一个名为的方法printTriangle(5);.我们需要创建一个迭代方法和一个递归方法(没有任何迭代).输出需要如下所示:

*
**
***
****
*****
Run Code Online (Sandbox Code Playgroud)

这段代码适用于迭代,但我无法使其适应递归.

public void printTriangle (int count) {
    int line = 1;
    while(line <= count) {
        for(int x = 1; x <= line; x++) {
            System.out.print("*");
        }
        System.out.print("\n");
        line++;
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该注意,你不能使用任何类级变量或任何外部方法.

Mic*_*ito 16

请注意,在迭代方法中,您有两个计数器:第一个是您所在的行line,第二个是您所在行的位置x.您可以创建一个递归函数,它接受两个参数并将它们用作嵌套计数器,yx.在递减x直到达到0的情况下,然后递减y并设置x = y,直到x和y都为0.

您还可以注意到三角形中的每个连续线都是前一行加一个星.如果递归函数返回前一行的一串星号,则下一行总是该字符串再加上一个星号.所以,你的代码将是这样的:

public String printTriangle (int count) {
    if( count <= 0 ) return "";

    String p = printTriangle(count - 1);
    p = p + "*";
    System.out.println(p);

    return p;
 }
Run Code Online (Sandbox Code Playgroud)


mik*_*iku 6

python中的示例(只是为了原型设计,但我希望这个想法能够通过):

#!/usr/bin/env python

def printTriangle(n):
    if n > 1:
        printTriangle(n - 1)
    # now that we reached 1, we can start printing out the stars 
    # as we climb out the stack ...
    print '*' * n

if __name__ == '__main__':
    printTriangle(5)
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

$ python 2717111.py
*
**
***
****
*****
Run Code Online (Sandbox Code Playgroud)

  • 我怀疑这将被视为迭代。 (2认同)