zoukankan      html  css  js  c++  java
  • leetcode Pascal's Triangle II

    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?

    Subscribe to see which companies asked this question

    大概有两天没有写leetcode了,手生了= =本来我就很怕杨辉三角形这种题,每次都不会。

    这道题是pascal's triangle II ,是返回特定层的数。

    pascal's triangle I是形成整个杨辉三角形,其实就是循环或者递归,我印象中那是我第一次用vector做题,做的不太会。

    回归这道题,刚开始我一直不太会,我认为不能生成整个三角形然后返回某层吧,但是如果不生成某层找规律我是没找到。

    看了别的方法,就是缓存前一层,但是生成的过程还是要有。

    这里二层循环的时候,j<tmp.size()我之前写的j<rowIndex属于概念理解不细心。

     1 class Solution {
     2 public:
     3     vector<int> getRow(int rowIndex) {
     4         vector<int> result;
     5         vector<int> tmp;
     6         result.push_back(1);
     7         if(rowIndex<=0) return result;
     8         for(int i=1;i<=rowIndex;i++){
     9             tmp=result;
    10             result.clear();
    11             result.push_back(1);
    12             for(int j=0;j<tmp.size()-1;j++){
    13                 result.push_back(tmp[j]+tmp[j+1]);
    14             }
    15             result.push_back(1);
    16         }
    17         return result;
    18     }
    19 };
  • 相关阅读:
    Study Plan The TwentySecond Day
    Study Plan The Nineteenth Day
    Study Plan The TwentySeventh Day
    Study Plan The Twentieth Day
    Study Plan The TwentyFirst Day
    python实现进程的三种方式及其区别
    yum makecache
    JSONPath 表达式的使用
    oracle执行cmd的实现方法
    php daodb插入、更新与删除数据
  • 原文地址:https://www.cnblogs.com/LUO77/p/5016937.html
Copyright © 2011-2022 走看看