★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-pvyiklzc-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.git
In Pascal's triangle, each number is the sum of the two numbers directly above it.github
Example:微信
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。app
在楊輝三角中,每一個數是它左上方和右上方的數的和。spa
示例:code
輸入: 5 輸出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
1 class Solution { 2 func generate(_ numRows: Int) -> [[Int]] { 3 var res:[[Int]] = [[Int]]() 4 if numRows <= 0 {return res} 5 var arr:[Int] = [Int]() 6 arr.append(1) 7 res.append(arr) 8 9 for i in 1..<numRows 10 { 11 var temp:[Int] = [Int]() 12 temp.append(1) 13 14 var count:Int = res[i - 1].count 15 for j in 1..<count 16 { 17 temp.append(res[i-1][j]+res[i-1][j-1]) 18 } 19 temp.append(1) 20 res.append(temp) 21 } 22 return res 23 } 24 }
8mshtm
1 class Solution { 2 func generate(_ numRows: Int) -> [[Int]] { 3 guard numRows > 0 else { 4 return [] 5 } 6 7 var temp = [[1]] 8 for i in 1..<numRows { 9 let last = temp[i - 1] 10 var arr = [Int]() 11 for j in 0...i { 12 var n : Int 13 if j == 0 { 14 n = 1 15 }else if j == i { 16 n = last[j - 1] 17 }else { 18 n = last[j] + last[j - 1] 19 } 20 arr.append(n) 21 } 22 temp.append(arr) 23 } 24 25 return temp 26 } 27 }
8msblog
1 class Solution { 2 func generate(_ numRows: Int) -> [[Int]] { 3 if numRows == 0 { return [] } 4 else if numRows == 1 { return [[1]] } 5 else if numRows == 2 { return [[1], [1,1]] } 6 7 var memo = [[1], [1,1]] 8 9 for i in 1..<numRows-1 { 10 let prevArr = memo[i] 11 var arr = Array(repeating: 0, count: prevArr.count+1) 12 arr[0] = 1 13 arr[arr.count-1] = 1 14 15 for j in 1..<arr.count-1 { 16 arr[j] = prevArr[j-1]+prevArr[j] 17 } 18 19 memo.append(arr) 20 } 21 22 return memo 23 } 24 }
12msrem
1 class Solution { 2 func generate(_ numRows: Int) -> [[Int]] { 3 if numRows == 0 { 4 return [] 5 } 6 var result = [[1]] 7 for i in 1...numRows { 8 var numRow = [Int]() 9 var lastNumRow = result[i - 1] 10 for j in 0..<i { 11 if j == 0 || j == i - 1 { 12 numRow.append(1) 13 } else { 14 numRow.append(lastNumRow[j - 1] + lastNumRow[j]) 15 } 16 } 17 result.append(numRow) 18 } 19 result.remove(at: 0) 20 return result 21 } 22 }