From 8c7eb9b21f9bfb6cca917b4eec5aaf5c295e4f83 Mon Sep 17 00:00:00 2001 From: bali-ibrahim Date: Fri, 12 Jan 2024 01:23:02 +0300 Subject: [PATCH] dev: leetcode --- leetcode/509.fibonacci-number.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 leetcode/509.fibonacci-number.go diff --git a/leetcode/509.fibonacci-number.go b/leetcode/509.fibonacci-number.go new file mode 100644 index 0000000..711adcb --- /dev/null +++ b/leetcode/509.fibonacci-number.go @@ -0,0 +1,19 @@ +func fib(n int) int { + var result [31]int + result[0] = 0 + result[1] = 1 + + if n > 1 { + result[n] = tailRec(n, [2]int{result[0], result[1]}) + } + + return result[n] +} + +func tailRec(n int, window [2]int) int { + if n == 1 { + return window[1] + } + + return tailRec(n-1, [2]int{window[1], window[0] + window[1]}) +}