内容
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 *k *行。
<small style="box-sizing: border-box; font-size: 12px;">在杨辉三角中,每个数是它左上方和右上方的数的和。</small>
示例:
<pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 9.5px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; background-color: rgb(245, 245, 245); border: 1px solid rgb(204, 204, 204); border-radius: 4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">输入: 3
输出: [1,3,3,1]
</pre>
进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?
思路
代码
/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function (rowIndex) {
if (rowIndex == 0) return [1];
if (rowIndex == 1) return [1, 1];
if (rowIndex == 2) return [1, 2, 1];
var save = [1, 2, 1];
for (var i = 3; i <= rowIndex; i++) {
var newArray = [];
for (var j = 0; j < save.length - 1; j++) {
newArray.push(save[j] + save[j + 1]);
}
newArray.unshift(1);
newArray.push(1);
save = newArray;
}
return save;
};