首页 > 其他 > 详细

[leetcode]Pascal's Triangle II

时间:2014-10-26 11:44:36      阅读:126      评论:0      收藏:0      [点我收藏+]

问题描述:

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?


思路:

the mth element of the nth row of the Pascal‘s triangle is C(n, m) = n!/(m! * (n-m)!)

C(n, m-1) = n!/((m-1)! * (n-m+1)!)

so C(n, m) = C(n, m-1) * (n-m+1) / m

In additional, C(n, m) == C(n, n-m)

代码:

public List<Integer> getRow(int rowIndex) {
		if(rowIndex < 0)
			return new ArrayList<Integer>();
		
		
		int num = rowIndex+1;
		List<Integer> list = new ArrayList<Integer>(num);
		
	
		double [] factor = new double[num];
		double result = 1;
		factor[0] = 1;
		list.add(1);
		for(int i=1; i<num ; i++){
			result = result*(num-i)/i;
			factor[i] = result;
			list.add((int)factor[i]);
		}
		return list;
        
        
    }


[leetcode]Pascal's Triangle II

原文:http://blog.csdn.net/chenlei0630/article/details/40475437

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!