算法一 直接找规律打印输出
/******************************
作者:cncoderalex
博客:http://blog.youkuaiyun.com/cncoderalex
/*******************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void PrintTriangle(int n)
{
int **ppAry = new int*[n];
for(int i = 0; i < n; i++)
{
ppAry[i] = new int[2*n];
memset(ppAry[i], 0, 2 * n * sizeof(int));
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i; j++)
{
if(j == 0)
ppAry[i][j] = 1;
else if(j == i)
ppAry[i][j] = 1;
else
ppAry[i][j] = ppAry[i-1][j-1] + ppAry[i-1][j];
}
}
printf("http://blog.youkuaiyun.com/cncoderalex");
printf("\n\n");
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n - i - 1; j++)
{
printf(" ");
}
for(int j = 0; j < i + 1; j++)
{
printf("%3d ", ppAry[i][j]);
}
printf("\n");
}
for(int i = 0; i < n; i++)
{
delete []ppAry[i];
}
delete []ppAry;
}
int main()
{
PrintTriangle(13);
system("pause");
return 0;
}
算法二 采用经典的二项式算法
/******************************
作者:cncoderalex
博客:http://blog.youkuaiyun.com/cncoderalex
/*******************************/
#include <stdio.h>
#include <stdlib.h>
int GetNum(int row, int col)
{
if(0 == col || row == col)
{
return 1;
}
int i;
int ans = 1;
for(i = 1; i <= col; i++)
{
ans = ans * (row - i + 1) / i;
}
return ans;
}
void PrintTriangle(int n)
{
printf("http://blog.youkuaiyun.com/cncoderalex");
printf("\n\n");
int i, j;
for(i = 0; i < n; i++)
{
for(j = 0; j < n - i - 1; j++)
{
printf(" ");
}
for(j = 0; j < i + 1; j++)
{
printf("%3d ", GetNum(i, j));
}
printf("\n");
}
}
int main()
{
PrintTriangle(13);
system("pause");
return 0;
}
本文地址:http://blog.youkuaiyun.com/cncoderalex/article/details/43225721 转载请标明出处,谢谢。