Question:

Given a non-negative index k where k ≤ 33, return the k index row of the Pascal’s triangle.

Note that the row index starts from 0.

119. Pascal's Triangle II - 图1
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

  1. Input: 3
  2. Output: [1,3,3,1]

Solution:

  1. /**
  2. * @param {number} rowIndex
  3. * @return {number[]}
  4. */
  5. var getRow = function(rowIndex) {
  6. let result=[];
  7. for(let i=0; i<rowIndex+1; i++){
  8. let item = [1]; //第一个元素
  9. if(i===1){
  10. item.push(1); //第二行
  11. }
  12. if(i>1){
  13. //循环上一个数组
  14. let arr = result[i-1];
  15. let sum;
  16. for(let j=0 ; j<arr.length-1; j++){
  17. sum = (arr[j]-0)+(arr[j+1]-0);
  18. item.push(sum);
  19. }
  20. item.push(1);//最后一个元素
  21. }
  22. result.push(item);
  23. }
  24. return result[rowIndex];
  25. };

Runtime: 52 ms, faster than 89.39% of JavaScript online submissions for Pascal’s Triangle II.