用迭代算法二项式系数c++
1 回答
小唯快跑啊
TA贡献1863条经验 获得超2个赞
这不就是求杨辉三角吗?
其递归公式如下
f(m,n)=1 当n=1或m=n时;
f(m,n)=f(m-1,n-1)+f(m-1,n) 当n>1且n<m时;
f(m,n)=0 其他。
以上,m,n均为大于0的整数。然后根据递归公式设计其迭代算法即可。
程序可如下
#include <iostream.h>
#include <conio.h>
void main()
{
int *preRow, *curRow, *tmp, m, row, col, i;
cin >> m;
preRow = new int(m+1);
curRow = new int(m+1);
for(i = 0; i <= m; i++) preRow[i] = curRow[i] = 0;
preRow[1] = curRow[1] = 1;
for(row = 2; row <= m; row++)
{
tmp = curRow, curRow = preRow, preRow = tmp;
curRow[1] = curRow[row] = 1;
for(col = 2; col < row; col++)
curRow[col] = preRow[col - 1] + preRow[col];
}
for(col = 1; col <= m; col++)
cout << curRow[col] << ' ';
delete(preRow);
delete(curRow);
getch( );
}
- 1 回答
- 0 关注
- 684 浏览
添加回答
举报
0/150
提交
取消