spaasteam / spaas-daily-practice

spaas团队的每日一练,欢迎小伙伴们提交踊跃答案!
4 stars 2 forks source link

第 53 题: 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 #66

Open GranzonLin opened 5 years ago

GranzonLin commented 5 years ago

杨辉三角,是二项式系数在三角形中的一种几何排列,它把二项式系数图形化,把组合数内在的一些代数性质直观地从图形中体现出来,是一种离散型的数与形的结合。

var generate = function(numRows) {
    //实现代码
};
Htongbing commented 5 years ago
const generate = numRows => {
  numRows = Math.floor(numRows)
  numRows = numRows >= 0 ? ++numRows : 1
  const result = []
  for (let i = 0; i < numRows; i++) {
    if (!result.length) {
      result.push([1])
      continue
    }
    const curRow = []
    const lastRow = result[result.length - 1]
    for (let j = 0; j < i + 1; j++) {
      j === 0 || !lastRow[j] ? curRow.push(1) : curRow.push(lastRow[j - 1] + lastRow[j])
    }
    result.push(curRow)
  }
  return result
}

console.log(generate(0)) // [ [ 1 ] ]
console.log(generate(1)) // [ [ 1 ], [ 1, 1 ] ]
console.log(generate(2)) // [ [ 1 ], [ 1, 1 ], [ 1, 2, 1 ] ]
console.log(generate(3)) // [ [ 1 ], [ 1, 1 ], [ 1, 2, 1 ], [ 1, 3, 3, 1 ] ]
console.log(generate(4)) // [ [ 1 ], [ 1, 1 ], [ 1, 2, 1 ], [ 1, 3, 3, 1 ], [ 1, 4, 6, 4, 1 ] ]
console.log(generate(5)) // [ [ 1 ], [ 1, 1 ], [ 1, 2, 1 ], [ 1, 3, 3, 1 ], [ 1, 4, 6, 4, 1 ], [ 1, 5, 10, 10, 5, 1 ] ]
console.log(generate(6)) // [ [ 1 ], [ 1, 1 ], [ 1, 2, 1 ], [ 1, 3, 3, 1 ], [ 1, 4, 6, 4, 1 ], [ 1, 5, 10, 10, 5, 1 ], [ 1, 6, 15, 20, 15, 6, 1 ] ]
cjfff commented 5 years ago
const generate = numRows => {
  const arr = Array.from({ length: numRows }, () => []);
  for (let i = 0; i < numRows; i++) {
    for (let j = 0; j <= i; j++) {
      if (j === 0 || j === i) {
        arr[i][j] = 1;
      } else {
        arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
      }
    }
  }
  return arr;
};

const markPrint = (A) => A.map((A, i) => "  ".repeat(10 - i) + A.join("   "))
    .join("\n")

console.log(markPrint(generate(10)));
/**
                    1
                  1   1
                1   2   1
              1   3   3   1
            1   4   6   4   1
          1   5   10   10   5   1
        1   6   15   20   15   6   1
      1   7   21   35   35   21   7   1
    1   8   28   56   70   56   28   8   1
  1   9   36   84   126   126   84   36   9   1
*/