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

leetcode 118. Pascal's Triangle && leetcode 119. Pascal's Triangle II

时间:2015-02-01 10:44:37      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

Given numRows, generate the first numRows of Pascal‘s triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
nextline[j] = currentline[j] + currentline[j+1]
 1 vector<vector<int> > generate(int numRows)
 2     {
 3         vector<vector<int> > pascal;
 4         vector<int> line;
 5 
 6         if (numRows <= 0)
 7             return pascal;
 8             
 9         line.push_back(1);
10         pascal.push_back(line);
11         if (numRows == 1)
12             return pascal;
13            
14         for (int i = 1; i < numRows; i++)
15         {
16             vector<int> nextLine;
17             
18             nextLine.push_back(1);
19             for (int j = 0; j < i - 1; j++)
20                 nextLine.push_back(line[j] + line[j + 1]);
21             nextLine.push_back(1);
22             pascal.push_back(nextLine);
23             line = nextLine;
24         }
25         
26         return pascal;
27     }

 

Given an index k, return the kth row of the Pascal‘s triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

 1 vector<int> getRow(int rowIndex) 
 2     {
 3         vector<int> line;
 4         vector<int> nextline;
 5         int numRows = rowIndex + 1;
 6 
 7         if (numRows <= 0)
 8             return line;
 9             
10         line.push_back(1);
11         if (numRows == 1)
12             return line;
13            
14         for (int i = 1; i < numRows; i++)
15         {
16             nextline.push_back(1);
17             for (int j = 0; j < i - 1; j++)
18                 nextline.push_back(line[j] + line[j + 1]);
19             nextline.push_back(1);
20             line = nextline;
21             nextline.clear();
22         }
23         
24         return line;
25     }

 

leetcode 118. Pascal's Triangle && leetcode 119. Pascal's Triangle II

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4265244.html

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