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

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取值范围不允许。

 

 

 

posted @ 2019-03-11 13:59  Archer-Fang  阅读(650)  评论(0编辑  收藏  举报