• 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;
        }
    }
  • 相关阅读:
    Winsock 2 入门指南
    Winsock 2 入门指南
    [手游新项目历程]-40-linux环境实现C/C++程序崩溃退出时打印栈信息
    1月下旬解题
    poj1226,poj3080
    poj3666
    poj3067
    poj12月其他题解(未完)
    poj1823,3667
    poj2352
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438451.html
Copyright © 2020-2023  润新知