leetcode笔记:Pascal's Triangle II

来源:互联网 发布:水晶球软件 储量计算 编辑:程序博客网 时间:2024/05/18 18:45

一. 题目描述

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?

二. 题目分析

关于帕斯卡三角形的定义,可参考:http://baike.baidu.com/link?url=qk_-urYQnO4v6v3P4BuMtCa0tMNUqJUk4lmbkb1aqbqikBU-ndiMlTF20fq2QUjTTFTeTohZ72KFxgBnz4sJha

该题要求只输出第k行的元素值,并且要求空间复杂度为O(k),因此,采用的方法是只使用一个定长的数组,用于存放每一行的元素值,对于每个新的行,可对原先存放的行从后往前扫描,主要分为以下三种情况:

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

这样,就只需要O(k)的空间。

三. 示例代码

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

四. 小结

若不要求O(k)的空间复杂度,该题的难度更低,但这样也没什么技巧可言了。

4 0
原创粉丝点击