【pascals-triangle-ii】

来源:互联网 发布:mysql编程题及答案 编辑:程序博客网 时间:2024/06/08 07:41

Given an index k, return the k th 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?


题意:输出指定行的帕斯卡三角形的值;并且要求空间负责度为o(k);因此采用的方法是只使用一个定长的数组,用于存储每一行的元素值,对于每个新的行,可对原先存放的行从后往前扫描,主要分为以下三种情况;

最后一个元素,直接等于1、对于下标为i的中间元素,有result[i]=result[i-1]+result[i];

最后一个元素,直接等于1;


class Solution{public:vector<int> getRow(int rowIndex){vector<int> result(rowIndex+1, 0);result[0] = 1;for (int i=1; i<rowIndex+1; i++){for (int j=i; j>=1; j--){result[j] += result[j-1];}}return result;}};


原创粉丝点击