2014.1.8 22:58
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?
Solution1:
Pascal's Triangle is a typical O(n^2) dynamic programming problem. Here is the recurrence relation:
1. f[i][0] = 1, i ∈ N
2. f[i][i] = 1, i ∈ N
3. f[i][j] = f[i - 1][j - 1] + f[i - 1][j], i ∈ N+, j ∈ N ∩ [0, i - 1]
From the recurrence relation we know that the calculation of current row depends only on the last row. Thus only O(k) extra space is needed.
Time complexity is O(n^2). Space complexity is O(n).
Accepted code:
1 // 1RE, 1AC 2 class Solution { 3 public: 4 vector<int> getRow(int rowIndex) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 8 int i, j; 9 result.clear(); 10 result.push_back(1); 11 for(i = 0; i < rowIndex; ++i){ 12 tmp.push_back(1); 13 for(j = 1; j <= i; ++j){ 14 // tmp[j] = result[j - 1] + result[j]; 15 // 1RE here, you haven't even pushed, how do you tmp[j] anyway??? 16 tmp.push_back(result[j - 1] + result[j]); 17 } 18 tmp.push_back(1); 19 result = tmp; 20 tmp.clear(); 21 } 22 23 return result; 24 } 25 private: 26 vector<int> result, tmp; 27 };
Solution2:
A little mathematical derivation can help us reach O(n) time complexity. See the three relations below:
1. f[i][j] = C(i, j);
2. C(i, j) = C(i, j - 1) * (i - j + 1) / j;
3. C(i, 0) = 1;
C stands for combination, please see reference here if you need some background knowledge.
Time complexity is O(n), space complexity is O(1). Generally mathematical formulae can help do things faster, because they change the time complexity to lower bound, at the cost of some labor on the brain. Guess that's why mathematicians thought they were smarter than computer scientists, huh? These stories do happen, especially on cryptography and informatics. Just go see "A Beautiful Mind" and read about John Nash.
Math is important, learn it well and enjoy it if you can.
Accepted code:
1 // 1AC, excellent 2 class Solution { 3 public: 4 vector<int> getRow(int rowIndex) { 5 result.clear(); 6 7 if(rowIndex < 0){ 8 return result; 9 } 10 11 long long int tmp; 12 13 tmp = 1; 14 result.push_back((int)tmp); 15 for(int i = 1; i <= rowIndex; ++i){ 16 tmp = tmp * (rowIndex - i + 1) / i; 17 result.push_back((int)tmp); 18 } 19 20 return result; 21 } 22 private: 23 vector<int> result; 24 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)