关于帕斯卡三角,不做过多论述,可以先查看百度百科以及leetcode。我将演示几种常用方法打印帕斯卡三角。相较于官方题解我会写的更加易懂,便于读者学习。
解法1,使用数组存储每一列(如果你没有学习过组合数学,这是一种常用解法)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36#include <stdio.h>
#define MAX 10
int main() {
int pascal[MAX][MAX] = {0};
int rows, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
pascal[i][0] = 1;
pascal[i][i] = 1;
for (j = 1; j < i; j++) {
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
}
}
for (i = 0; i < rows; i++) {
for (j = 0; j < rows - i; j++) {
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("%4d", pascal[i][j]);
}
printf("\n");
}
return 0;
}另附leetcode的官方题解:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19int** generate(int numRows, int* returnSize, int** returnColumnSizes) {
int** c = malloc(numRows * sizeof(int*));
*returnSize = numRows;
*returnColumnSizes = malloc(numRows * sizeof(int));
for (int i = 0; i < numRows; i++) {
(*returnColumnSizes)[i] = i + 1;
c[i] = malloc((i + 1) * sizeof(int));
c[i][0] = c[i][i] = 1;
for (int j = 1; j < i; j++) {
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
}
return c;
}解法2,使用二项式系数公式单独计算每一个值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40#include <stdio.h>
int binomialCoeff(int n, int k);
int main() {
int rows, coef;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (int i = 0; i < rows; i++) {
for (int space = 1; space <= rows - i; space++)
printf(" ");
for (int j = 0; j <= i; j++) {
coef = binomialCoeff(i, j);
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
int binomialCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}解法3,基于解法2,我们也许还可以用递归来写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51#include <stdio.h>
void printPascalTriangle(int rows, int row);
int binomialCoeff(int n, int k);
int main() {
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printPascalTriangle(rows, 0);
return 0;
}
void printPascalTriangle(int rows, int row) {
if (row >= rows)
return;
for (int space = 0; space < rows - row - 1; space++) {
printf(" ");
}
for (int j = 0; j <= row; j++) {
printf("%4d", binomialCoeff(row, j));
}
printf("\n");
printPascalTriangle(rows, row + 1);
}
int binomialCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}