一維數組實現楊輝三角,維數楊輝三角

來源:互聯網
上載者:User

一維數組實現楊輝三角,維數楊輝三角

楊輝三角Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 43411    Accepted Submission(s): 18254


Problem Description還記得中學時候學過的楊輝三角嗎?具體的定義這裡不再描述,你可以參考以下的圖形:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
 
Input輸入資料包含多個測試執行個體,每個測試執行個體的輸入只包含一個正整數n(1<=n<=30),表示將要輸出的楊輝三角的層數。 
Output對應於每一個輸入,請輸出相應層數的楊輝三角,每一層的整數之間用一個空格隔開,每一個楊輝三角後面加一個空行。 
Sample Input
2 3
 
Sample Output
11 111 11 2 1
 
Authorlcy 
SourceC語言程式設計練習(五)  


import java.util.Scanner;public class Main {    static int[] mat = new int[31];    public static void main(String args[]) {        Scanner sc = new Scanner(System.in);        mat[0] = 1;// 初始化第一個元素,也就是第一列的值全為1;        int n = 0;        while (sc.hasNext()) {            n = sc.nextInt();            triangle(n);        }    }    public static void triangle(int n) {        System.out.println(mat[0]);        mat[n - 1] = 1;// 從後面往前面        for (int i = 1; i < n; i++) {// 控制行數            mat[i] = 1;            for (int j = i - 1; j > 0; j--) {                mat[j] = mat[j] + mat[j - 1];                if (mat[j] < 0) {                    return;                }            }            for (int j = 0; j <= i; j++) {                if (j == 0) {                    System.out.print(mat[j]);                } else {                    System.out.print(" " + mat[j]);                }            }            System.out.println();        }        System.out.println();    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.