算法基礎4:求解楊輝三角m層的第n個元素(遞歸)

進行視頻j學習的時候發現了一個題目 是這樣的
在這裏插入圖片描述
先上源代碼

public class Demo6 {

	public static void main(String[] args) {
		int level = 5;
		for(int i=0; i<=level; i++) {
			System.out.print(f(level,i)+" ");
		}

	}

	private static int f(int level, int n) {
		if(n == 0) return 1;
		if(level == n) return 1;
		return f(level-1, n) + f(level-1, n-1);
	}

}

做題之前我們得先了解一下 楊輝三角是什麼 順道瞭解一下楊輝三角如何進行實現

楊輝三角概述(百度百科)

楊輝三角,是二項式係數在三角形中的一種幾何排列,

在這裏插入圖片描述
那麼楊輝三角是怎麼實現的呢:?(兩種方式 遞歸和非遞歸 )
這裏借鑑了一下「時光·漫步zth」的原創文章
原文鏈接:https://blog.csdn.net/qq_41573234/article/details/83107460
非遞歸方式:

import java.util.Scanner;

public class Demo7 {

	public static void main(String[] args) {
		//通過輸入的數字判斷楊慧三角的行數
		@SuppressWarnings("resource")
		Scanner input = new Scanner(System.in);
		System.out.print("輸入行數:");
		int n = input.nextInt();
		
		//定義一個二維數組
		int[][] array = new int[n][];
		f(array,n);
	}
	//開始打印楊慧三角
	private static void f(int[][] array, int n) {
		if (n < 0) return;
		for(int i=0; i<array.length; i++) {			
			array[i] = new int[i+1];		      
		   // 打印空格
			System.out.printf("%" + (array.length - i)*2 + "s", "");		       
		      for (int j = 0; j < array[i].length; j++) {
		    	  //判斷左右兩邊,因爲兩邊均爲一
		        if(j == 0 || array[i].length-1 == j) {		        
		          array[i][j] = 1;
		        }else {
		          // 其他元素等於頭頂上兩位數字之和
		          array[i][j] = array[i-1][j] + array[i-1][j-1];
		        }
		        System.out.printf("%4d",array[i][j]);
		      }
		     System.out.println();
		 }		
	}

}

遞歸實現

import java.util.Scanner;

public class Demo8 {
	
	public static void main(String[] args) {
		 @SuppressWarnings("resource")
		Scanner input = new Scanner(System.in);
		 System.out.print("輸入行數:");
		 int max = input.nextInt();   	
		 if (max < 0) return;
		    for (int i=0; i<max; i++) {
		      
		      //打印空格
		      for (int j=1; j<=max-i-1; j++) {
		        System.out.print("  ");
		      }
		      //打印數字
		      for (int j=1; j<= i; j++) {
		    	  //以4位整數的形式輸出
		        System.out.printf("%4d",f(i,j));
		      }
		      	//換行
		      System.out.println();
		    }
	}
	//遞歸實現
	public  static  int f(int i,int j) {
		if (j == 1 || i== j) {			
	        return 1;
	    }else {
	      return f(i-1,j)+f(i-1,j-1);
	    }
	 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章