Pascal's Triangle II

来源:互联网 发布:根据域名添加路由设置 编辑:程序博客网 时间:2024/06/17 10:22

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?

思路:法  1 : 从前往后  ret.set(j , pre.get(j - 1) + pre.get(j));   法  2 : 从后往前 ret.set(j , ret.get(j - 1) + ret.get(j));

易错点: 如果从前往后, 必须设置一个 pre 作为 copy , 因为在加的过程中会有变化.
如果从后往前, 则不用再加一个 pre 作为 buffer. 但是一定要注意  j  从 i - 1 开始。

public class Solution {    public List<Integer> getRow(int rowIndex) {        List<Integer> ret = new ArrayList<Integer>();        if(rowIndex < 0)            return ret;        ret.add(1);        for(int i = 1; i <= rowIndex; i++){            List<Integer> pre = new ArrayList<Integer>(ret);            for(int j = 1; j < i; j++){                ret.set(j , pre.get(j - 1) + pre.get(j));            }            ret.add(1);        }        return ret;    }}
<pre name="code" class="java">public class Solution {    public List<Integer> getRow(int rowIndex) {        List<Integer> ret = new ArrayList<Integer>();        if(rowIndex < 0)            return ret;        ret.add(1);        for(int i = 1; i <= rowIndex; i++){            ret.add(1);            for(int j = i - 1; j >= 1; j--){                ret.set(j , ret.get(j - 1) + ret.get(j));            }        }        return ret;    }}






0 0
原创粉丝点击