杨辉三角求特定的行中的各个数字

The rows of Pascal's triangle are conventionally enumerated starting with row n = 0 at the top (the 0th row). The entries in each row are numbered from the left beginning with k = 0 and are usually staggered relative to the numbers in the adjacent rows. The triangle may be constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero entry 1. Each entry of each subsequent row is constructed by adding the number above and to the left with the number above and to the right, treating blank entries as 0. For example, the initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers 1 and 3 in the third row are added to produce the number 4 in the fourth row.

Pascal's Triangle

 

思路:

因为对于特定的行列有如下公式:

Binomial Coefficient

 

所以

 C(lineNumber, i) = lineNumber! / ((lineNumber - i)! * i!)

C(lineNumber, i - 1) = lineNumber! / ((lineNumber - i + 1)! * (i - 1)!)

可以推出
C(lineNumber, i) = C(lineNumber, i - 1) * (lineNumber - i + 1) / i
即直接从当前行推出当前行的各个数字。

代码如下:

const currentLine = [1];

const currentLineSize = lineNumber + 1;

 for (let numIndex = 1; numIndex < currentLineSize; numIndex += 1) {
    currentLine[numIndex] = currentLine[numIndex - 1] * (lineNumber - numIndex + 1) / numIndex;
  }

 

  思路2:

递归求,根据上一行的数求当前行的数。

不能直接由公式求当前行的特定数,因为int取值范围不允许。

 

 

 

转载于:https://www.cnblogs.com/Archer-Fang/p/10510221.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值