Dynamic Programming I: Day 1
Diffstat:
2 files changed, 34 insertions(+), 0 deletions(-)
@@ -1,3 +1,4 @@
// memorization approach
class Solution {
public:
int fib(int n) {
@@ -8,3 +9,18 @@
public:
return f[n];
}
};
// optimized, memorize only the previous two values
class Solution {
public:
int fib(int n) {
if (n == 0) return 0;
int a = 0, b = 1;
for (int i = 2; i <= n; i++) {
int tmp = a + b;
a = b;
b = tmp;
}
return b;
}
};
@@ -1,3 +1,4 @@
// memorization approach
class Solution {
public:
int tribonacci(int n) {
@@ -9,3 +10,20 @@
public:
return f[n];
}
};
// optimized, memorize only the previous three values
class Solution {
public:
int tribonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
int a = 0, b = 1, c = 1;
for (int i = 3; i <= n; i++) {
int tmp = a + b + c;
a = b;
b = c;
c = tmp;
}
return c;
}
};