代码之家  ›  专栏  ›  技术社区  ›  Alec Gorge

只使用递归从星星中创建一个三角形

  •  9
  • Alec Gorge  · 技术社区  · 16 年前

    我需要写一个方法 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++;
        }
    }
    

    10 回复  |  直到 13 年前
        1
  •  18
  •   Michael Petito    10 年前

    注意在您的迭代方法中,您有两个计数器:第一个是您所在的行 line ,第二个是你在这条线上的位置 x y

    你也可以注意到三角形中的每一条连续的线都是前一条线加上一颗星。如果递归函数为前一行返回一个星号字符串,那么下一行总是该字符串加上一个星号。所以,你的代码应该是这样的:

    public String printTriangle (int count) {
        if( count <= 0 ) return "";
    
        String p = printTriangle(count - 1);
        p = p + "*";
        System.out.println(p);
    
        return p;
     }
    
        2
  •  6
  •   miku    16 年前

    #!/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
  •  3
  •   SLaks    16 年前

    void printStars(int count) {
        if (count == 0) return;
    
        System.out.print("*");
        printStars(count - 1);
    }
    printStars(5);    //Prints 5 stars
    

        4
  •  2
  •   Eyal Schneider    16 年前

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

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

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

        5
  •  0
  •   escargot agile    16 年前

    该方法以恒星数作为参数。我们叫它n。

    1. 使用n-1递归调用自身。

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

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

        6
  •  0
  •   Carl Manaster    16 年前
    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);
        }
    
    }
    
        7
  •  0
  •   Fareed Alnamrouti    15 年前
        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);
            }
    
        8
  •  0
  •   Muhaimin Tahsin    5 年前
    #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);
    }
    
        9
  •  -1
  •   Kelsey    16 年前

    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"); 
    }
    
        10
  •  -1
  •   Jerry    16 年前

    所以,你需要创建一个小的块。那个街区需要什么信息?只是最大值。但是递归需要知道它在哪条线上。。。你会得到一个构造函数,比如:

    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);
    
        11
  •  -1
  •   Razakii    7 年前

    我想应该这样做

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