码迷,mamicode.com
首页 > 其他好文 > 详细

Pascal's Triangle Pascal's Triangle||

时间:2014-09-23 00:43:43      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:leetcode   pascals triangle pas   

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]
]

Pascal‘s Triangle||:

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?

Pascal‘s triangle.

public class Solution {
	public List<List<Integer>> generate(int numRows) {
	    if(numRows == 0){
			return new ArrayList<List<Integer>>();
		}
		List<List<Integer>> ans = new ArrayList<List<Integer>>();
		ans.add(new ArrayList<Integer>(Arrays.asList(1)));
		for(int i=1;i<numRows;i++){
			List<Integer> list = new ArrayList<Integer>();
			for(int j=0;j<=i;j++){
				if(j==0||j==i){
					list.add(1);
					continue;
				}
				list.add(ans.get(i-1).get(j-1)+ans.get(i-1).get(j));
			}
			ans.add(list);
		}
		return ans;
	}
}

Pascal‘s Triangle||:

public class Solution {
    	public List<Integer> getRow(int rowIndex) {
		List<Integer> ans = new ArrayList<Integer>();
		for(int i=0;i<=rowIndex;i++){
			List<Integer> temp = new ArrayList<Integer>();
			for(int j=0;j<=i;j++){
				if(j==0||j==i){
					temp.add(1);
					continue;
				}
				temp.add(ans.get(j)+ans.get(j-1));
			}
			ans = new ArrayList<Integer>(temp);
		}
		return ans;
	}
}


其实这些基本处理就是学习C语言时的杨辉三角。

 

 

Pascal's Triangle Pascal's Triangle||

标签:leetcode   pascals triangle pas   

原文地址:http://blog.csdn.net/huruzun/article/details/39483083

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!