LeetCode pascals-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].

Note:
Could you optimize your algorithm to use only O(k) extra space?

题意:简单的来说就是打印出杨辉三角的(K+1)行

解题思路,用两个List,一个list保存上一行的记录,一个List用来计算当前行的记录

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public ArrayList<Integer> getRow(int rowIndex) {
        if (rowIndex < 0)
            return null;
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        if (rowIndex == 0)
            return list;

        for (int i = 0; i < rowIndex; i++) {
            ArrayList<Integer> cur = new ArrayList();
            cur.add(1);
            for (int j = 0; j < list.size() - 1; j++) {
                cur.add(list.get(j) + list.get(j + 1));
            }
            cur.add(1);
            list = cur;
        }

        return list;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        List list = s.getRow(0);
        System.out.println(list);
    }
}

 

posted @ 2016-09-01 14:26  googlemeoften  阅读(146)  评论(0编辑  收藏  举报