Pascal's Triangle

问题描述

 

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,

Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

 

解决思路

初始条件 + 循环控制。

 

程序

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (numRows <= 0) {
            return res;
        }
        
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        res.add(list);
        if (numRows == 1) {
            return res;
        }
        
        list = new ArrayList<Integer>();
        list.add(1);
        list.add(1);
        res.add(list);
        if (numRows == 2) {
            return res;
        }
        
        for (int i = 2; i < numRows; i++) {
            List<Integer> tmp = res.get(i - 1);
            List<Integer> add = new ArrayList<Integer>();
            add.add(1);
            for (int j = 0; j < i - 1; j++) {
                add.add(tmp.get(j) + tmp.get(j + 1));
            }
            add.add(1);
            res.add(add);
        }
        
        return res;
    }
}

 

Follow up

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? 

 

解决思路

辅助的中间list存上一个list的结果。交替进行。

 

程序

public class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> row = new ArrayList<Integer>();
        if (rowIndex < 0) {
            return row;
        }
        
        row.add(1);
        if (rowIndex == 0) {
            return row;
        }
        
        row.add(1);
        if (rowIndex == 1) {
            return row;
        }
        
        List<Integer> tmp = new ArrayList<Integer>(row);
        int i = 2;
        
        while (i <= rowIndex) {
            int mids = i - 1;
            row = new ArrayList<Integer>();
            row.add(1);
            for (int j = 0; j < mids; j++) {
                row.add(tmp.get(j) + tmp.get(j + 1));
            }
            row.add(1);
            tmp = new ArrayList<Integer>(row);
            ++i;
        }
        
        return row;
    }
}

  

posted @ 2015-07-24 09:10  Chapter  阅读(130)  评论(0编辑  收藏  举报