Pascal's Triangle II <leetcode>
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 vector<int> getRow(int rowIndex) { 4 vector<int> temp(rowIndex+1); 5 vector<int> pre(rowIndex+1); 6 pre[0]=1; 7 for(int i=0;i<=rowIndex;i++) 8 { 9 temp[0]=1; 10 temp[i]=1; 11 for(int j=1;j<i;j++) 12 { 13 temp[j]=pre[j-1]+pre[j]; 14 } 15 pre=temp; 16 } 17 return temp; 18 } 19 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步