码迷,mamicode.com
首页 > 其他好文 > 详细

打印杨辉三角

时间:2015-06-26 09:20:20      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:c++

#include <iostream>
#include <iomanip>
using namespace std;
int * setRow(int rowId, int * lastRow){
    int * row = new int[rowId];
    row[0] = 1;
    for(int i = 1;i < rowId - 1;i++){
        row[i] = lastRow[i - 1] + lastRow[i];
    }
    row[rowId - 1] = 1;
    return row;
}
void printRow(int rowId, int * row){
    for(int i = 0;i < rowId;i++){
        cout <<setw(4)<<row[i];
    }
    cout <<endl;
}

int main(){
    int * tri = new int[2];
    tri[0] = 1;
    tri[1] = 1;

    int rowNum = 3;
    cin >>rowNum;
    int * row;
    bool ret = true;
    for(int i = 3; i <= rowNum; ++i){
        if(ret){
            row = setRow(i, tri);
            printRow(i, row);
            delete [] tri;
            tri = NULL;
        }else{
            tri = setRow(i, row);
            printRow(i, tri);
            delete [] row;
            row = NULL;
        }
        ret = !ret;
    }
    if(ret){
        delete [] row;
        row = NULL;
    }else{
        delete [] tri;
        tri = NULL;
    }
}
#include <iostream>
#include <iomanip>
using namespace std;

int main(void){
    int rowNum = 3;
    cout <<"enter row number here:";
    cin >>rowNum;
    int * row = new int[rowNum + 1];
    //very important!
    for(int i = 0;i < rowNum + 1 ; ++i){
        row[i] = 0;
    }
    int * p = row;
    p[1] = 1;
    cout.setf(ios::left);
    for(int i = 1;i < rowNum + 1 ; ++i){
        //print ith row
        for(p += i; p != row; --p){//亮点
            cout <<setw(2) <<(*p += *(p-1)) << setw(2)<<‘ ‘;
        }
        cout <<endl;
    }

}

第二段代码第i+1个位置开始填充第i行,只需维护一个数组

打印杨辉三角

标签:c++

原文地址:http://blog.csdn.net/u011450367/article/details/46642303

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!