Recursive to Iterative Pascal's Triangle

后端 未结 3 1073
面向向阳花
面向向阳花 2021-01-26 00:51

I wonder how to convert a recursive function/class to an iterative one. I have made a recursive Pascal\'s triangle, and now need to compare it to an iterative.

p         


        
相关标签:
3条回答
  • 2021-01-26 01:31

    Here's the code for recursive pascal triangle,

    import java.util.Scanner;
    
    public class PascalsTriangleRecursion 
    {
       public static void printPascal(int num)
       {
          for(int a = 0; a < num; a++)
          {
             for(int b = 0; b <= a; b++)
             {
                System.out.print(pascalTriangle(a, b) + " ");
             }
             System.out.println();
          }
       }
    
       public static int pascalTriangle(int a, int b)
       {
          if(b == 0)
          {
             return 1;
          }
          else if(b == a)
          {
             return 1;
          }
          else
          {
             return pascalTriangle(a - 1, b - 1) + pascalTriangle(a - 1, b);
          }
       }
    
       public static void main(String[] args) 
       {
          Scanner sc = new Scanner(System.in);
          System.out.print("Please enter number of rows : ");
          int number = sc.nextInt();
          printPascal(number);
          sc.close();
       }
    }
    

    For more info on pascal triangle refer this resource.

    0 讨论(0)
  • 2021-01-26 01:33

    Go through this link you will find your answer explained in detail http://www.geeksforgeeks.org/pascal-triangle/

    0 讨论(0)
  • 2021-01-26 01:43

    Plug these two functions below into a pascal class. I tested it and it works. That link that Prateek Darmwal posted is pretty much the same thing.

      public void nonRecursivePrint()
      {
        nonRecursivePrint(n, true);
      }
    
      public void nonRecursivePrint(int n, boolean upsideDown)
      {
        if (!upsideDown)
        {
          for (int j=0; j<(n+1); j++)
          {
            for (int i=0; i<(j); i++)
            {
              System.out.print(binom(j - 1, i) + (j == i + 1 ? "\n" : " "));
            }
          }
        }
        else
        {
          for (int j=n; j>0; j--)
          {
            for (int i=0; i<(j); i++)
            {
            System.out.print(binom(j - 1, i) + (j == i + 1 ? "\n" : " "));
            }
          }
        }       
      }
    
    0 讨论(0)
提交回复
热议问题