java楊輝三角

       自從參加完藍橋杯之後就沒再怎麼好好學習java算法了,最近公司事情不多,剛好利用閒暇時間複習和整理一下對算法的學習。今天就先複習一下當年很苦逼的楊輝三角:
            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
思路:首先定義一個二維數組:data[row][row].當row=1和2的時候皆爲1.(這裏的1,2是正常自然數來數的而非數組下標)。當row>2時,data[row][0]和data[row][row]皆爲1(每一行的首尾皆爲1)。而每一行的其他項data[row][i] = data[row-1][i-1]+data[row-1][i]  。此種有規律的算法題個人思路就是以前4個項來推斷出通用的通式。當年總覺得楊輝三角很難,網上的各種例子也很複雜,其實濾清思路的話解題路子就清晰了。當然這算法是沒考慮什麼效率的啦。哈哈

以下是代碼:
import java.util.Scanner;

public class yanghui {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int row = scan.nextInt();
int data[][] = new int[row][row];
data[0][0] = 1 ;
data[1][0] = 1 ;
data[1][1] = 1 ;
for(int i = 2 ; i < row ; i++){
data[i][0] = data[i][i] = 1 ;
for(int j = 1 ; j < i ; j++){
data[i][j] = data[i-1][j-1]+data[i-1][j];
}
}
for(int i = 0 ; i < row ; i++){
for(int j = 0 ; j < row ; j++){
if(data[i][j]!=0){
System.out.print(data[i][j]+" ");
}
}
System.out.println();
}
}
}
發佈了35 篇原創文章 · 獲贊 133 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章