题目: 采用递归计算过程计算出帕斯卡三角形的各个元素。
row:
0 1
1 1 1
2 1 2 1
3 1 3 3 1
4 1 4 6 4 1
5 . . . . . .
col: 0 1 2 3 4
//c++ //递归 #include<iostream> using namespace std; int pascaler(int row ,int col){ int value; if(col>row) { cout<<"error"<<endl; } else if(col==0||row==col){ value = 1; } else { value=(pascaler((row-1),col))+(pascaler((row-1),(col-1))); } return value; } int main() { int row,col; cin>>row>>col; cout<<pascaler(row,col)<<endl; return 0; } //迭代 #include<iostream> using namespace std; int pascaliter(int product,int count,int n) { int value; int max_count=n; if(count>max_count){ value = product; } else { value=pascaliter((count*product),(count+1),max_count); } return value; } int pascalclcu(int row,int col){ int valuex; valuex = (pascaliter(1,1,row)/((pascaliter(1,1,col))*(pascaliter(1,1,(row-col))))); return valuex; } int main() { int row,col; cin>>row>>col; cout<<pascalclcu(row,col)<<endl; return 0; }
时间: 2024-11-09 10:54:26