A: hi! ~ Hello, everyone, I am YK bacteria 🐷, a front-end microsystem ✨, like to share their small knowledge 🏹, welcome to follow me 😘 ~ [wechat account: YK2012YK2012, wechat official account: ykyk2012]

Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Medium, difficult question I am submissive, simple question I punch attack, today to do a simple question to increase self-confidence, Yang Hui triangle. This one looks easy, but there are some details that can go wrong

118. Yang Hui Triangle

Link: leetcode-cn.com/problems/pa…

Given a non-negative integer numRows, generate the former numRows of the “Yang Hui triangle”. In Yang Hui’s triangle, each number is the sum of the numbers on its upper left and upper right.

A double cycle

We just need to write the code according to the definition of the topic. For specific ideas, you can see the comments in the code

/ * * *@param {number} numRows
 * @return {number[][]}* /
function generate(numRows) {
  // Create a result array. The elements of the array are still arrays, i.e. a two-dimensional array
  let result = [];
  // The ith element in the result array is the ith element in the triangle (I starts at 0).
  for (let i = 0; i < numRows; i++) {
    // define a row array in the triangle, row I has I +1 elements, the content is filled with 1
    let row = new Array(i + 1).fill(1);
    // Iterate over the array of rows and populate it with results
    for (let j = 1; j < row.length - 1; j++) {
      // Each number is the sum of its upperleft and upperright numbers
      row[j] = result[i - 1][j - 1] + result[i - 1][j];
    }	
    // Push row into result array
    result.push(row);
  }
  // Return an array of trigonometric results
  return result;
}
Copy the code

The results