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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…