Pascal's Triangle II

本文介绍如何使用优化算法在O(k)额外空间内返回Pascal三角形的第k行,并提供了求组合数的公式及实现方法。

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?

 

A Formula for Any Entry in The Triangle

In fact there is a formula from Combinations for working out the value at any place in Pascal's triangle:

It is commonly called "n choose k" and written like this:

So Pascal's Triangle could also be an "n choose k" triangle like this: (Note how the top row is row zero and also the leftmost column is zero)


Pascals Triangle Combinations


This can be very useful ... you can now work out any value in Pascal's Triangle 
directly (without calculating the whole triangle above it).Example: Row 4, term 2 in Pascal's Triangle is "6" ...

... let's see if the formula works:

Yes, it works! Try another value for yourself.

 1 public class Solution {
 2     public ArrayList<Integer> getRow(int rowIndex) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         ArrayList<Integer> result = new ArrayList<Integer>();
 6         for(int i = 0; i <= rowIndex; i ++){
 7             result.add(items(rowIndex, i));
 8         }
 9         return result;
10     }
11     public int items(int m, int n){ // m!/ (n!(m-n)!)
12         int i = m;
13         long ret = 1;
14         for (int j = 1; j <= n; j ++){
15             ret *= i --;
16             ret /= j;
17         }
18         return (int)ret;
19     }
20 }

注意的地方是ret要用long,用int会溢出。

转载于:https://www.cnblogs.com/reynold-lei/p/3427469.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值