LeetCode 119. Pascal's Triangle

2020-04-25  本文已影响0人  洛丽塔的云裳

0. 题目

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.


1. c++ 版本

方式1: 使用递归,当前行rowIndex的内容是依赖rowIndex获取,但是递归,存在临时变量赋值的问题,失败了,原因待查

方式2: 直接使用循环. 计算rowIndex 就是计算从0~rowIndex-1的内容,然后进行计算

    vector<int> passcal(vector<int>& nums) {
        int len = nums.size();
        int newlen = len + 1;
        vector<int> rows(newlen);
        rows[0] = rows[len] = 1;
        for (int i=1; i<=len/2; ++i) {
            rows[i] = rows[len-i] = nums[i-1] + nums[i];
        }
        return rows;
    }
    
    vector<int> getRow(int rowIndex) {
         vector<int> rows;
         rows.push_back(1);
         if (rowIndex == 0) 
             return rows;
         int i = 1;
         while (i<= rowIndex) {
             rows = passcal(rows);
             ++i;
         }
        return rows;
    }

c++ 最简单版本,但是很难理解 https://leetcode.com/problems/pascals-triangle-ii/discuss/38454/Sharing-my-c%2B%2B-code-very-simple

    vector<int> getRow(int rowIndex) {
        vector<int> res(rowIndex+1,1);
        for(int i=2;i<=rowIndex;i++) { // 总共1~rowIndex
            for(int j=i-1;j>=1;j--) // 每行元素的倒数第二个值开始计算
                res[j]=res[j]+res[j-1];
        }
        return res;

2. python 版本

思路同c++版本,注意python语言的特色

class Solution(object):
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        rows = []
        rows.append(1)
        if rowIndex == 0: return rows
        for i in range(1, rowIndex+1):
            length = len(rows)
            next = (length+1)*[0]
            next[0] = next[-1] = 1
            for j in range(1, length/2+1):
                next[j] = next[length-j] = rows[j-1] + rows[j]
            rows = next
        return rows

python 语言优化版本。https://leetcode.com/problems/pascals-triangle-ii/discuss/38467/Very-simple-Python-solution

上一篇下一篇

猜你喜欢

热点阅读