Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update tribonacci_using_DP.cpp #168

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 25 additions & 26 deletions tribonacci_using_DP.cpp
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
#include <iostream>
#include <map>
#include <vector>

using namespace std;
int tribonacci(int n) {
// Base cases
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;

class Tribo {
public:
int calc(int n, map<int, int> &memo) {
if (memo.find(n) != memo.end()) {
return memo[n];
} else {
int sol = calc(n - 1, memo) + calc(n - 2, memo) + calc(n - 3, memo);
memo[n] = sol;
return sol;
}
}
// Create a vector to store the Tribonacci numbers
std::vector<int> dp(n + 1, 0);

// Initialize base cases
dp[0] = 0;
dp[1] = 1;
dp[2] = 1;

int tribonacci(int n) {
map<int, int> memo;
memo[0] = 0;
memo[1] = 1;
memo[2] = 1;

return calc(n, memo);
// Fill the dp vector using the Tribonacci formula
for (int i = 3; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
}
};

// Return the nth Tribonacci number
return dp[n];
}

int main() {
Tribo t;
int n;
cout << "Enter a number: ";
cin >> n;
int result = t.tribonacci(n);
cout << "Tribonacci of " << n << " is: " << result << endl;
std::cout << "Enter the value of n: ";
std::cin >> n;

int result = tribonacci(n);
std::cout << "The " << n << "th Tribonacci number is: " << result << std::endl;

return 0;
}