【算法练习】(7)杨辉三角

题目描述

输入n值,使用递归函数,求杨辉三角形中各个位置上的值。
输入描述:

一个大于等于2的整型数n
输出描述:

题目可能有多组不同的测试数据,对于每组输入数据,
按题目的要求输出相应输入n的杨辉三角形。

示例1

输入

6

输出

1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

代码实现:

#include<iostream>
using namespace std;
int tri(int row,int col){
    if(row==0 || col==0 || row==col) return 1;
    else if(col<row){
        return tri(row-1,col-1)+tri(row-1,col);
    }else return 1;
}
int main(){
    int n;
    while(cin>>n){
        if(n>=2){
            for(int i=1;i<n;i++){
                for(int j=0;j<=i;j++){
                    cout<<tri(i,j);
                    if(i!=j)
                        cout<<" ";
                }
                cout<<'\n';
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_24734285/article/details/79422110