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

时间:2010-04-26 21:41:03

标签: java recursion

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

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

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

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

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

11 个答案:

答案 0 :(得分: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;
 }

答案 1 :(得分:4)

您可以将循环转换为递归函数,如下所示:

void printStars(int count) {
    if (count == 0) return;

    System.out.print("*");
    printStars(count - 1);
}
printStars(5);    //Prints 5 stars

您应该能够创建类似的功能来打印线条。

答案 2 :(得分:4)

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)

输出如下:

$ python 2717111.py
*
**
***
****
*****

答案 3 :(得分:2)

您也可以使用单个(不那么优雅)的递归来完成,如下所示:

public static void printTriangle (int leftInLine, int currLineSize, int leftLinesCount) {
    if (leftLinesCount == 0)
        return;
    if (leftInLine == 0){ //Completed current line?
        System.out.println();
        printTriangle(currLineSize+1, currLineSize+1, leftLinesCount-1);
    }else{
        System.out.print("*");
        printTriangle(leftInLine-1,currLineSize,leftLinesCount);
    }
}

public static void printTriangle(int size){
    printTriangle(1, 1, size);
}

这个想法是方法参数表示完整的绘图状态。

请注意,大小必须大于0。

答案 4 :(得分:0)

你可以这样做:

该方法将星数作为参数。我们称之为n。

然后呢:

  1. 以n-1递归调用。

  2. 打印一条有n个星的行。

  3. 如果n == 0,请确保不执行任何操作。

答案 5 :(得分:0)

package playground.tests;

import junit.framework.TestCase;

public class PrintTriangleTest extends TestCase {
    public void testPrintTriangle() throws Exception {
        assertEquals("*\n**\n***\n****\n*****\n", printTriangleRecursive(5, 0, 0));
    }

    private String printTriangleRecursive(int count, int line, int character) {
        if (line == count)
            return "";
        if (character > line)
            return "\n" + printTriangleRecursive(count, line + 1, 0);
        return "*" + printTriangleRecursive(count, line, character + 1);
    }

}

答案 6 :(得分:0)

    void trianglePrint(int rows){
            int static currentRow = 1;
            int static currentStar = 1;

            // enter new line in this condition
            // (star > currentrow)  

            if (currentStar > currentRow ){
                currentStar = 1;
                currentRow++;
                cout << endl;
            }

            if (currentRow > rows){
                return; // finish
            }

            cout << "*";
            currentStar++;

            trianglePrint(rows);
        }

答案 7 :(得分:0)

#include<iostream>
using namespace std;
 void ll__(int x){
  char static c = '0'; // character c will determine when to put newline
  if(!x){
    if(c=='1'){
      cout<<'\n';
    }
    return;
  }
  if(c=='0'){
    ll__(x-1); //  rows to be called in the stack and differentiated by character '0'
  }
  if(x==1 && c=='0'){
   cout<<'*';
  }else{  // columns to be printed in every row as per the row number in the stack
   c = '1';
   ll__(x-1);
   cout<< '*';
  }
}

int main(){
//writes code here
 ll__(5);
 exit(0);
}

答案 8 :(得分:-1)

我认为这应该有效......我的头脑中没有经过考验。

public void printTriangle(int count)
{    
    if (count == 0) return;
    printTriangle(count - 1);
    for (int x = 1; x <= count; x++) { 
        System.out.print("*"); 
    }
    System.out.print("\n"); 
}

答案 9 :(得分:-1)

所以,你需要创建一个小块。该块需要哪些信息?只是最大的。但是递归需要知道它在哪个行上......你最终会得到一个像:

这样的构造函数
public void printTriangle (int current, int max)

现在,使用它将其余的递归放在一起:

public void printTriangle (int current, int max)
{ 
    if (current <= max) 
    { 
         // Draw the line of stars...
         for (int x=0; x<current; x++)
         {
             System.out.print("*")
         }
         // add a newline
         System.out.print("\n"); 

         // Do it again for the next line, but make it 1-bigger
         printTriangle(current + 1, max);
    } 
} 

现在,您所要做的就是启动它:

printTriangle(1, 5);

答案 10 :(得分:-1)

我认为应该这样做

public void printTriangle (int count) {
   if(count >= 0) {
      printTriangle(count-1);
          for(int i = 0; i < count; i++) {
              System.out.print("*" + " ");
          }
      System.out.println(); 
   }
}
相关问题