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 關注
- 725 瀏覽
添加回答
舉報
