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;
    }
}

 

posted @ 2015-04-19 00:11  YRB  阅读(448)  评论(0编辑  收藏  举报