仅使用递归创建星形三角形 [英] Create a triangle out of stars using only recursion

查看:114
本文介绍了仅使用递归创建星形三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to to write a method that is called like printTriangle(5);. We need to create an iterative method and a recursive method (without ANY iteration). The output needs to look like this:

*
**
***
****
*****

此代码适用于迭代,但我无法使其适应递归。

This code works with the iterative but I can't adapt it to be recursive.

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++;
    }
}

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

I should note that you cannot use any class level variables or any external methods.

推荐答案

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

Notice in your iterative approach that you have two counters: the first is what line you are on line, and the second is what position on the line you are on x. You could create a recursive function that takes two parameters and uses them as nested counters, y and x. Where you decrement x until it reaches 0, then decrement y and set x = y, until both x and y are 0.

您还可以注意到每个连续的行三角形是前一行加一颗星。如果你的递归函数返回前一行的一串星星,那么下一行总是那个字符串加一个星号。因此,您的代码将类似于:

You could also notice that each successive line in the triangle is the previous line plus one star. If your recursive function returns a string of stars for the previous line, the next line is always that string plus one more star. So, your code would be something like:

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

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

    return p;
 }

这篇关于仅使用递归创建星形三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆