int* getRow(int rowIndex, int* returnSize) {
if (rowIndex < 0)
return NULL;
int *res = (int*)malloc(sizeof(int) * (rowIndex + 1));
for (int row = 0; row <= rowIndex; row++)
for (int col = row; col >= 0; col--)
res[col] = (col == 0 || col == row) ? 1 : res[col] + res[col - 1];
*returnSize = rowIndex + 1;
return res;
}
主要方法是采用倒序,从后往前加,每次循环逐个覆盖。
第一次外循环 1
第二次外循环 1 1
第三次外循环 1 2 1
第三次外循环 1 3 3 1
规律如果col == row或col == 0 则res[col] = 1,否则res[col] = res[col] + res[col – 1];仅覆盖了res[col].
递归实现
int rowget(int x,int y)
{
if(y == 0)
return 1;
if(x < y)
return 0;
return rowget(x-1,y)+rowget(x-1,y-1);
}
int* getRow(int rowIndex, int* returnSize) {
int *rowarray,*head,i;
*returnSize = rowIndex+1;
rowarray = (int *)malloc((rowIndex+1)*sizeof(int));
head = rowarray;
for(i = 0;i<=rowIndex;i++)
{
*rowarray = rowget(rowIndex,i);
rowarray++;
}
return head;
}
递归实现:耗时太长,不宜使用。
输出n阶杨辉三角
#include <stdio.h>
#include <stdlib.h>
int* getRow(int rowIndex) {
int row,col,*res;
if (rowIndex < 0)
return NULL;
res = (int*)malloc(sizeof(int) * (rowIndex + 1));
for (row = 0; row <= rowIndex; row++)
for (col = row; col >= 0; col–)
res[col] = (col == 0 || col == row) ? 1 : res[col] + res[col – 1];
return res;
}
int main()
{
int *head,i,j,k;
int n;
scanf(“%d”,&n);
for(i = 0;i<=n;i++)
{
head = getRow(i);
for(k = 0;k<n-i;k++)
printf(” “);
for(j = 0;j <= i;j++)
{
printf(“%3d”,*head);
printf(” “);
head++;
}
printf(“\n”);
}
return 0;
}