## 如何实现Java三角递归？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (65)

``````****
***
**
*
``````

``````   *
**
***
****
``````
``````public static String printTriangle(int num)
{
if (num == 0) {
return "";
}

String dots = "";
for (int i = 0; i < num; i++) {
dots = dots + "*";
}

System.out.println(dots);
return printTriangle(num-1) + dots;
}

public static String printTriangle2(int num) {
if (num == 0) {
return "";
}

String dots = printTriangle2(num-1);
dots = dots + ".";

String spaces = "";
for (int i = 0; i < num; i++) {
spaces = spaces + " ";
}

String line = spaces + dots;
System.out.println(line);
return line;
}
``````

``````****
***
**
*
.
..
...
....``````

### 2 个回答

``````printTriangle(4,0)
printTriangle2(4,0)

public static String printTriangle(int num, int step)
{
if (num == 0) {
return "";
}

String ast = "";
for (int i = 0; i < num; i++) {
ast = ast + "*";
}
String sps = "";
for (int i = 0; i < step; i++) {
sps = sps + " ";
}

System.out.println(sps+ast);
return printTriangle(num-1, step+1) ;
}
``````
``````    public static String printTriangle2(int num, int step)
{
if (num == 0) {
return "";
}

String ast = "";
for (int i = 0; i <= step; i++) {
ast = ast + "*";
}
String sps = "";
for (int i = 0; i < num; i++) {
sps = sps + " ";
}

System.out.println(sps+ast);
return printTriangle2(num-1, step+1) ;
}``````

``````static void printTriangle(int n, int len)
{
if(n == len) return;

printRow(n, len);
printTriangle(n+1, len);
printRow(n, len);
}

static void printRow(int n, int len)
{
for(int i=0; i<n; i++) System.out.print(" ");
for(int i=n; i<len; i++) System.out.print("*");
System.out.println();
}
``````

``````printTriangle(0, 4);
``````

``````****
***
**
*
*
**
***
****
``````

``````static void printTriangle(String s)
{
if(!s.contains("*")) return;

System.out.println(s);
printTriangle(" " + s.replaceFirst("\\*", ""));
System.out.println(s);
}
``````

``printTriangle("****");``