From fdbf72a5bcd437182494a3896711e05502d4e10b Mon Sep 17 00:00:00 2001 From: Chiranjeev <6258860@gmail.com> Date: Wed, 27 Oct 2021 17:08:48 +0530 Subject: [PATCH] added nth-tribonacci problem --- Leetcode/DP/N-th Tribonacci Number.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Leetcode/DP/N-th Tribonacci Number.cpp diff --git a/Leetcode/DP/N-th Tribonacci Number.cpp b/Leetcode/DP/N-th Tribonacci Number.cpp new file mode 100644 index 0000000..09499d9 --- /dev/null +++ b/Leetcode/DP/N-th Tribonacci Number.cpp @@ -0,0 +1,25 @@ +/* + Approach Used: Bottom-up Dynamic Programming + + F(N) = F(N-1) + F(N-2) + F(N-3), so using the fact that we only need last three values, we can build up the solution taking first 3 values of F(0) = 0, F(1) = 1, F(2) = 1, and build the solution upto N using previous three values. + + Time Complexity: O(n) + Space Complexity: O(1) + + */ + +class Solution { +public: + int tribonacci(int n) { + if(n == 0)return 0; + int first = 0, second = 1, third = 1; + for(int i=3; i <= n; i++){ + int fourth = first + second + third; + first = second; + second = third; + third = fourth; + } + + return third; + } +}; \ No newline at end of file