Last active
December 26, 2021 19:56
Swift Pascal Triangle Recursive Solution (not optimized)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func solve(_ numRows: Int, _ result: [[Int]]?) -> [[Int]] { | |
guard numRows > 0 else { | |
return [] | |
} | |
var tmp = [[Int]]() | |
var tmpIndex = 0 | |
if let result = result { | |
tmp = result | |
tmpIndex = result.count + 1 | |
} else { | |
tmpIndex += 1 | |
} | |
if tmpIndex == 1 { tmp.append([1]) } | |
if tmpIndex > 1 { | |
var row = [Int]() | |
for i in 0...tmpIndex { | |
if i == 0 { row.append(1) } | |
if i == (tmpIndex - 1) { row.append(1) } | |
if i > 0 && i < tmpIndex - 1 { row.append(tmp[tmpIndex-2][i-1] + tmp[tmpIndex-2][i])} | |
} | |
tmp.append(row) | |
} | |
if numRows == tmp.count { | |
return tmp | |
} else { | |
return solve(numRows, tmp) | |
} | |
} |
For a better presentation of the result you can use the following code:
let rowNumber = 10
print("Pascal Triangle for row \(rowNumber) is: ")
let pt = solve(rowNumber, nil)
for row in pt {
print(row)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then just call it the following way: