C语言一维数组实现杨辉三角,一维数组实现杨辉三角
楊輝三角
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
1
1 1
1
1 1
1 2 1
Author
lcy
Source
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();
}
}
原文:http://blog.csdn.net/hncu1306602liuqiang/article/details/46408971
總結
以上是生活随笔為你收集整理的C语言一维数组实现杨辉三角,一维数组实现杨辉三角的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle裁员原因_Oracle大幅度
- 下一篇: python画鱼_Python经典五人分