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

[leetcode]Pascal's Triangle II

时间:2014-10-26 11:46:08      阅读:251      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!