Pascal's Triangle II

来源:互联网 发布:aes算法过程 编辑:程序博客网 时间:2024/06/09 13:55


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?


有一种只需要开辟一个数组的解法,有时间补上。


这道题的思路跟第一问很像,一种解决思路是使用两个数组,pre, cur 不断的更新。

代码:

public List<Integer> getRow(int rowIndex) {        //可以用数学公式计算        List<Integer> cur = new ArrayList<>();        List<Integer> pre = new ArrayList<>();        pre.add(1);        if(rowIndex == 0) return pre;        for(int i=1;i<=rowIndex;i++){            cur.clear();            cur.add(1);            for(int j=1;j<pre.size();j++){                cur.add(pre.get(j) + pre.get(j-1));            }            cur.add(1);            //pre.clear();            //System.out.println(cur.size());            pre.clear();            pre.addAll(cur);        }        return pre;    }


还有一种解法:只需要一个数组

public List<Integer> getRow(int rowIndex) {        List<Integer> list = new ArrayList<Integer>();        if(rowIndex <0){            return list;        }        for(int i=0;i<rowIndex+1;i++){            //首位的1            list.add(0,1);            for(int j=1;j<list.size()-1;j++){                list.set(j, list.get(j)+list.get(j+1));            }            //末尾的1就不动它        }        return list;    }


0 0