zoukankan      html  css  js  c++  java
  • 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].

    链接: http://leetcode.com/problems/pascals-triangle-ii/

    题解:

    跟上题一样。

    Time Complexity - O(n),Space Complexity - O(1)。

    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> res = new ArrayList<>();
            
            for(int i = 0; i <= rowIndex; i++) {
                res.add(0, 1);
                
                for(int j = 1; j < res.size() - 1; j++)
                    res.set(j, res.get(j) + res.get(j + 1));    
            }
            
            return res;
        }
    }

    二刷:

    和Pascals Triangle I一样。主要的点是 k = 0的时候, 结果等于1, k = 1的时候,结果为11。 题目没说清楚,不过并没有什么影响,知道方法就可以了。

    Java:

    Time Complexity - O(n),Space Complexity - O(k)。

    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> res = new ArrayList<>();
            if (rowIndex < 0) {
                return res;
            }
            for (int i = 0; i <= rowIndex; i++) {
                res.add(1);
                for (int j = res.size() - 2; j >= 1; j--) {
                    res.set(j, res.get(j) + res.get(j - 1));
                }
            }
            return res;
        }
    }

    三刷:

    上面的复杂度算错了。 同时要注意k = 0的时候结果为{1},以此类推。

    Java:

    Time Complexity - O(k ^2),Space Complexity - O(k)。

    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> res = new ArrayList<>();
            if (rowIndex < 0) {
                return res;
            }
            for (int i = 0; i <= rowIndex; i++) {
                res.add(1);
                for (int j = res.size() - 2; j >= 1; j--) {
                    res.set(j, res.get(j) + res.get(j - 1));
                }
            }
            return res;
        }
    }

    Update:

    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> res = new ArrayList<>();
            if (rowIndex < 0) return res;
            for (int i = 0; i <= rowIndex; i++) {
                res.add(1);
                for (int j = res.size() - 2; j > 0; j--) {
                    res.set(j, res.get(j) + res.get(j - 1));
                }
            }
            return res;
        }
    }
  • 相关阅读:
    margin和pading的百分比值
    Vue中的computed和watch
    JS的自身属性和继承属性
    JS对象的可枚举属性和不可枚举属性
    Dart语言学习
    Practice_Test
    Lesson2 basic python_20200920
    Python 基础语法L1
    小男孩和狗的故事
    智者的故事
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438451.html
Copyright © 2011-2022 走看看