如何使用递归打印三角形?



我有一个作业,我需要使用递归打印一个三角形图案,如下所示:

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

它是通过调用triangle(4)生成的。这是我的代码:

public static void triangle(int height) {
if (height == 0) {
return;
}
triangle(height - 1);
print_rowhelper(height, height - 1);
}
public static void print_row(int x) {
for (int i = 0; i < x; i++) {
System.out.print("*");
}
System.out.println();
}

public static void print_rowhelper(int x, int y) {
print_row(x);
for (int i = 0; i<= y - 1; i++) {
y -= 1;
System.out.print("*");
}
System.out.println();
}

我已经移动了变量,我完成的最好的事情就是这个......

*
**
***
****

。当代码按以下方式编写时:

public static void triangle(int height) {
if (height == 0) {
return;
}
triangle(height - 1);
print_row(height);
}

当我试图让它减少时,我碰壁了。

您应该添加有关width变化方向的信息:+1或"-1"。最初inc = 1row == height时应更改为inc = -1

public static void triangle(int height) {
triangle(1, 1, 1, height);
}
private static void triangle(int row, int width, int inc, int height) {
if (width == 0)
return;
for (int i = 0; i < width; i++)
System.out.print('*');
System.out.println();
if (row == height)
inc = -1;
triangle(row + 1, width + inc, inc, height);
}

输出:

triangle(4);
System.out.println();
triangle(5);

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

我想再补充一个例子:

class Main {

private static void triangle(int n, int i) {
printStars(i);
if (i < n) {
triangle(n, i + 1);
printStars(i);
}
}


static void triangle(int n) {
triangle(n, 1);
}


static void printStars(int n) {
for (int i = 0; i < n; ++i) {
System.out.print('*');
}
System.out.print('n');
}


public static void main(String[] args) {
triangle(4);
}
}

诀窍是在两个打印语句之间使用递归。您可以使用递归调用以三角形两侧的星形形式打印其深度。因此,我们在这里使用了递归调用分层的事实。

最新更新