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

    题目:

    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?

    题意及分析:求杨辉三角的第k行,第一行下标为0.

    代码:

    class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> list = new ArrayList<>();
            for(int i=1;i<=rowIndex+1;i++){       //分别求出每一行
                List<Integer> newList = new ArrayList<>();
                newList.add(0,1);  //第一个数为1
                for(int k=1;k<i-1;k++){
                    newList.add(k,list.get(k)+list.get(k-1));
                }
                if(i>1)newList.add(1);
                list = newList;
            }
            return list;
        }
    }

     或者,每一行从后往前求的话可以复用,不用新建一个临时list,可以节约空间

    class Solution {
        public List<Integer> getRow(int rowIndex) {     //获取第杨辉三角的第rowIndex行,空间复杂度为o(rowIndex)
            List<Integer> list = new ArrayList<>();
            for(int i=0;i<rowIndex+1;i++){       //分别求出每一行
                list.add(1);
                for(int k=i-1;k>0;k--){
                    list.set(k,list.get(k)+list.get(k-1));
                }
            }
            return list;
        }
    }

     

  • 相关阅读:
    1月10日 TextView
    1月9日 布局2
    30 Adapter适配器
    29 个人通讯录列表(一)
    28 ListView控件
    27 登录模板
    26 Activity的启动模式
    25 Activity的生命周期
    24 得到Activity返回的数据
    23 Activity的传值2(bundle)
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7813577.html
Copyright © 2011-2022 走看看