[Swift]LeetCode118. 杨辉三角 | Pascal's Triangle
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9709270.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 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 }
8ms
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 }
8ms
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 }
12ms
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了