zoukankan      html  css  js  c++  java
  • LeetCode OJ 119. Pascal's Triangle II

    119. 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?


    【思路】

    一刷:我们为了满足空间复杂度的要求,我们新建两个ArrayList,一个负责存储上一个Pascal行的结果,一个根据上一个Pascal行得出当前Pascal行的结果,这个过程循环进行。

    二刷:ArrayList的操作是比较慢的,这次我们用数组来对结果进行存储。数组保存上一个状态,通过上一个状态计算下一个状态。例如:[1,3,3,1],我们可以从最后一个元素开始,num[i] = num[i] + num[i-1]。最后我们再在末尾补1。这样能大大提高代码的效率。


    【java代码一刷】

     1 public class Solution {
     2     public List<Integer> getRow(int rowIndex) {
     3         List<Integer> prelist = new ArrayList<>();
     4         prelist.add(1);
     5         if(rowIndex <= 0) return prelist;
     6         List<Integer> curlist = new ArrayList<>();
     7         for(int i = 1; i <= rowIndex; i++){
     8             curlist.add(1);
     9             for(int j = 0; j < prelist.size() - 1; j++){
    10                 curlist.add(prelist.get(j) + prelist.get(j+1));
    11             }
    12             curlist.add(1);
    13             List<Integer> temp = prelist;
    14             prelist = curlist;
    15             curlist = temp;
    16             curlist.clear();
    17         }
    18         return prelist;
    19     }
    20 }

     


    【java代码二刷】

     1 public class Solution {
     2     public List<Integer> getRow(int rowIndex) {
     3         int[] nums = new int[rowIndex+1];
     4         for(int i = 0; i <= rowIndex; i++) {
     5             for(int j = i; j >= 1; j--)
     6                 nums[j] += nums[j-1];
     7             nums[i] = 1;
     8         }
     9         
    10         List<Integer> res = new ArrayList<>(rowIndex);
    11         for(int num : nums) res.add(num);
    12         return res;
    13     }
    14 }
     
  • 相关阅读:
    async 和 await
    Nginx配置反向代理与负载均衡
    简单使用高德地图开放平台API
    layui select 动态赋值
    ERROR: Pool overlaps with other one on this address space
    解决docker镜像无法删除的问题
    伪静态问题导致前台页面无法通过地址栏访问
    ERROR: Failed to Setup IP tables: Unable to enable SKIP DNAT rule
    PHP使用引用实现无限极分类
    composer update -- memory_limit
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5512977.html
Copyright © 2011-2022 走看看