zoukankan      html  css  js  c++  java
  • LeetCode: Pascal's Triangle II 解题报告

    Pascal's Triangle II

    Total Accepted: 19384 Total Submissions: 63446 My Submissions Question Solution
    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?

    解:
    题目里要求O(k),与上一题 杨辉三角 类似,但是我们稍微改一下,只需要存上一行的结果就行了。
    这样就不需要消耗太多内存。

    更厉害的是:Inplace也可以,只要你每次从后往前扫描就行了。一个array也能搞定:

     1 public class Solution {
     2     public List<Integer> getRow(int rowIndex) {
     3         List<Integer> ret = new ArrayList<Integer>();
     4         
     5         for (int i = 0; i <= rowIndex; i++) {
     6             for (int j = i; j >= 0; j--) {
     7                 if (j == i) {
     8                     ret.add(1);
     9                 } else if (j != 0) {
    10                     // ERROR: use add instead of set
    11                     //ret.add(ret.get(j) + ret.get(j - 1));
    12                     ret.set(j, ret.get(j) + ret.get(j - 1));
    13                 }
    14             } 
    15         }
    16         
    17         return ret;
    18     }
    19 }
    View Code


    GitHub代码链接

  • 相关阅读:
    闭包问题小总结
    git常用命令总结
    数组对象方法的使用
    JS截取URL参数
    CSS清除浮动&内容居中&文字溢出
    网址大全
    any more
    下载网页视频
    下载无损音乐
    "前端" 宝藏网站
  • 原文地址:https://www.cnblogs.com/yuzhangcmu/p/4194823.html
Copyright © 2011-2022 走看看