标签: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