Skip to content

Instantly share code, notes, and snippets.

@spaquet
Last active December 26, 2021 19:56
Show Gist options
  • Save spaquet/9c6e245990ab4741ad6ef86e10203f96 to your computer and use it in GitHub Desktop.
Save spaquet/9c6e245990ab4741ad6ef86e10203f96 to your computer and use it in GitHub Desktop.
Swift Pascal Triangle Recursive Solution (not optimized)
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)
}
}
@spaquet
Copy link
Author

spaquet commented Dec 26, 2021

Then just call it the following way:

print("Pascal Triangle for row is: ")
let pt = solve(10, nil)
print(pt)

@spaquet
Copy link
Author

spaquet commented Dec 26, 2021

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