NthCatalan returns the n-th Catalan Number Complexity: O(n²)
(n int)
| 13 | // NthCatalan returns the n-th Catalan Number |
| 14 | // Complexity: O(n²) |
| 15 | func NthCatalanNumber(n int) (int64, error) { |
| 16 | if n < 0 { |
| 17 | //doesn't accept negative number |
| 18 | return 0, errCatalan |
| 19 | } |
| 20 | |
| 21 | var catalanNumberList []int64 |
| 22 | catalanNumberList = append(catalanNumberList, 1) //first value is 1 |
| 23 | |
| 24 | for i := 1; i <= n; i++ { |
| 25 | catalanNumberList = append(catalanNumberList, 0) //append 0 and calculate |
| 26 | |
| 27 | for j := 0; j < i; j++ { |
| 28 | catalanNumberList[i] += catalanNumberList[j] * catalanNumberList[i-j-1] |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | return catalanNumberList[n], nil |
| 33 | } |
no outgoing calls