--- tags: Data Structure I, LeetCode disqus: HackMD --- # 巴斯卡三角形(Pascal's Triangle) ## 虛擬碼 ```pseudocode= ``` ## 解題 [118. Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/description/?envType=study-plan&id=data-structure-i) ### 題目說明 給定一個整數,返回帕斯卡三角形的第一個 numRows。 在帕斯卡三角形中,每個數位都是其正上方兩個數位的總和,如下所示:   ### 解法 第一種 **Javascript** 除每行**最左側**與**最右側**的數字以外,每個數字等於它的**左上方與右上方兩個數字之和**。 ```javascript= /** * @param {number} numRows * @return {number[][]} */ var generate = function(numRows) { if (numRows == 0) return []; let a_num = [[1]]; for (let i = 1 ; i < numRows ; i ++) { let p_num = a_num[i - 1]; let b_num = [1]; //第一位一定為1 for (let j = 1 ; j < i ; j ++) { let x = parseInt(p_num[j - 1]); let y = parseInt(p_num[j]); b_num.push([x+y]); } b_num.push([1]);//最後一位一定為1 a_num.push(b_num); } return a_num; }; ``` > [name=@denny0628] [time=Tue, Nov 23, 2022 14:45 PM] [color=#907bf7]
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.