題目
難度級別:簡單
給定一個非負索引 k,其中 k ≤ 33,返回楊輝三角的第 k 行。
在楊輝三角中,每個數是它左上方和右上方的數的和。
示例:
輸入: 3
輸出: [1,3,3,1]
進階:
你可以優化你的算法到 O(k) 空間複雜度嗎?
解題思路
法一
解法與楊輝三角思路一樣。
const getRow = function(rowIndex) {
let res = [1]
if (rowIndex === 0) return res
for (let j = 0; j < rowIndex; j++) {
const currentLine = [1]
const len = res.length
for (let i = 0; i < len; i++) {
if (i + 1 === len)
currentLine.push(1)
else
currentLine.push(res[i] + res[i + 1])
}
res = currentLine
}
return res
};
法二
通過動態規劃,因爲當前元素的值等於他的左上角於右上角之和(除開左右2邊元素),考慮到不佔用額外空間,所以可以採用在楊輝三角前一位補零,然後每次遍歷到的當前元素,就修改爲當前元素索引與它的索引+1之和,最後一位不做遍歷修改。
例:
[0,1,3,3,1], 第3層
[0+1,1+3,3+3,3+1,1] 第四層 即 [1,4,6,4,1]
const getRow = function(rowIndex) {
let res = [1]
if (rowIndex === 0) return res
for (let j = 0; j < rowIndex; j++) {
res.unshift(0)
for (let i = 0; i < j + 1; i++) {
res[i] = (res[i] + res[i + 1])
}
}
return res
};
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/pascals-triangle-ii