题目1073：杨辉三角形

6

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

2002年清华大学计算机研究生机试真题(第I套)

 1 #include<iostream>
2 #include<vector>
3 using namespace std;
4 vector<int> getYang(int n){
5   vector<int> atN;
6   if(n == 1){
7     atN.push_back(1);
8     atN.push_back(1);
9   }
10   else{
11     vector<int> preLevel = getYang(n-1);
12     for(int i = 0; i < preLevel.size();i++){
13       cout<<preLevel[i];
14       if(i != preLevel.size()-1) cout<<" ";
15       else cout<<endl;
16     }
17     atN.push_back(1);
18     int p1 = 0,p2 = 1;
19     while(n-- > 1){
20       atN.push_back(preLevel[p1] + preLevel[p2]);
21       p1++; p2++;
22     }
23     atN.push_back(1);
24   }
25   return atN;
26 }
27 int main(){
28   int n;
29   while(cin>>n) getYang(n);
30   return 0;
31 }

 1 #include<vector>
2 #include<iostream>
3 using namespace std;
4 int main(){
5     int n;
6     while(cin>>n){
7         vector<int> va,vb;
8         va.push_back(1);
9         va.push_back(1);
10         vb.push_back(1);
11         vector<int> *vSource = &vb,*vPrint = &va,*tmp = NULL;
12         while(--n >0){
13             for(int i =0; i<vPrint->size(); i++){
14                 cout<<(*vPrint)[i];
15                 if(i != vPrint->size() -1) cout<<" ";
16                 else cout<<endl;
17             }
18             tmp = vPrint;
19             vPrint = vSource;
20             vSource = tmp;
21             int p1=0,p2=1;
22             while(p2 < vSource->size()){
23                 int value = (*vSource)[p1] + (*vSource)[p2];
24                 if(p2 < vPrint->size()) (*vPrint)[p2] = value;
25                 else vPrint->push_back(value);
26                 p1++;
27                 p2++;
28             }
29             vPrint->push_back(1);
30         }
31     }
32     return 0;
33 }

posted on 2013-03-04 09:02  denallo  阅读(1126)  评论(0编辑  收藏  举报