【49】119. Pascal's Triangle II

119. Pascal's Triangle II

Description Submission Solutions Add to List

  • Total Accepted: 102894
  • Total Submissions: 291602
  • Difficulty: Easy
  • Contributors: Admin

 

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 class Solution {
 2 public:
 3 //杨辉三角从0层开始往下,第n层的第k个是Cnk(k在上面)
 4 //本地调试输出前十行,没啥问题,拿到OJ上测试,程序在第18行跪了,中间有个系数不正确。那么问题出在哪了呢,仔细找找,原来出在计算组合数那里,由于算组合数时需要算连乘,而整形数int的数值范围只有-32768到32768之间,那么一旦n值过大,连乘肯定无法计算。
 5 /*
 6    vector<int> getRow(int rowIndex) {
 7         vector<int> out;
 8         if (rowIndex < 0) return out;
 9         
10         for (int i = 0; i <= rowIndex; ++i) {
11             if ( i == 0 || i == rowIndex)
12                 out.push_back(1);
13             else
14                 out.push_back (computeCnk(rowIndex, i));
15         }
16         return out;
17     }
18     
19     int computeCnk(int n, int k) {
20         if (k > n) return 0;
21         else if (k > n/2) k = n - k;
22         int numerator = 1, denomator = 1;
23         for (int i = 0; i < k; ++i) {
24             numerator *= n - i;
25             denomator *= k - i;
26         }
27         if (denomator != 0) return numerator/denomator;
28         else return 0;
29     }*/
30     
31     vector<int> getRow(int rowIndex) {
32         vector<int> out(rowIndex + 1, 0);
33         //if (rowIndex < 0) return out;
34         
35         //out.assign(rowIndex + 1, 0);
36         for (int i = 0; i <= rowIndex; ++i) {
37             if ( i == 0) {
38                 out[0] = 1;
39                 continue;
40             }
41             for (int j = rowIndex; j >= 1; --j) {
42                 out[j] = out[j] + out[j-1];
43             }
44         }
45         return out;
46     }
47    
48 };

 

posted @ 2017-02-10 09:25  会咬人的兔子  阅读(178)  评论(0编辑  收藏  举报