1. 程式人生 > >Java——列印楊輝三角(遞迴和非遞迴)

Java——列印楊輝三角(遞迴和非遞迴)

1.  非遞迴方法: 

package com.zth;
/**
 * 列印楊輝三角
 * @author 時光·漫步
 *
 */
public class SanJiao {

  public static void main(String[] args) {
    // 定義陣列的長度
    int length = 10;
    int arr[][] = new int[length][];
    
    // 遍歷二維陣列
    for (int i = 0; i < arr.length; i++) {
      // 確定二維陣列元素的大小
      arr[i] = new int[i+1];
      
      // 列印空格
      for (int j = 0; j < arr.length-i-1; j++) {
        System.out.print("  ");
      }
       
      // 遍歷一維陣列
      for (int j = 0; j < arr[i].length; j++) {
        if(j == 0 || arr[i].length-1 == j) {
          // 三角形兩腰全為 1
          arr[i][j] = 1;
        }else {
          // 其他元素等於兩肩數字之和
          arr[i][j] = arr[i-1][j] + arr[i-1][j-1];
        }
        System.out.printf("%4d",arr[i][j]);
      }
      System.out.println();
    }
  }

}

執行結果:

                     1
                   1   1
                 1   2   1
               1   3   3   1
             1   4   6   4   1
           1   5  10  10   5   1
         1   6  15  20  15   6   1
       1   7  21  35  35  21   7   1
     1   8  28  56  70  56  28   8   1
   1   9  36  84 126 126  84  36   9   1

2. 遞迴方法:

package com.zth;

public class SanJiao1 {

  public  static  int fun(int i,int j) {
    if(j == 1 || i == j) {
      return 1;
    }else {
      return fun(i-1,j)+fun(i-1,j-1);
    }
  }
  public static void main(String[] args) {
    int length = 10;    // 列印的行數
    
    for (int i = 1; i <= length; i++) {
      
      // 列印空格
      for (int j = 1; j <= length-i; j++) {
        System.out.print("  ");
      }
      for (int j = 1; j <= i; j++) {
        System.out.printf("%4d",fun(i,j));
      }
      System.out.println();
    }
  }

}

執行結果:

                     1
                   1   1
                 1   2   1
               1   3   3   1
             1   4   6   4   1
           1   5  10  10   5   1
         1   6  15  20  15   6   1
       1   7  21  35  35  21   7   1
     1   8  28  56  70  56  28   8   1
   1   9  36  84 126 126  84  36   9   1