Tribonacci numbers (and, in general, K-bonacci numbers) are defined not with 2 base cases (1, 1) and the rule to add the two predecessors, but K base cases and the rule to add the K predecessors.
The good news is that they look very similar to traditional Fibonacci, so the
intuitive solution (the elegant recursive solution) comes naturally to almost
anyone who has solved traditional Fibonacci.
The bad news is that they look very similar to traditional Fibonacci, so the
same problems encountered with it also apply to these extended Fibonacci-like
sequences, namely, that the complexity grows way out of hand even more quickly
for K-bonacci than for Fibonacci.
Fibonacci grew at 2^n because the rule was to add the 2 previous terms. Tribonacci
(add the previous 3), then, will grow at 3^n (2^10 is about 1,000; 3^10 is about
59,000); 4-bonacci will grow at 4^n (2^10 is about 1,000; 4^10 is about 1,050,000)
and so on.
Any Fibonacci-type sequence like this will grow at a rate of K^n, where K is
the number of terms you have to compute to get the next one (2 for Fibonacci; 3
for Tribonacci; 4 for 4-bonacci; etc.)
However, you don’t need to panic if you ever see K-bonacci sequences in a
homework assignment or interview. You know the strategy to make Fibonacci more
efficient, and if it works for Fibonacci with 2 base cases, then it’ll work for
Tribonacci with 3 base cases, and so on: don’t throw away the work you’ve
already done. This becomes especially critical with bigger K-value K-bonacci
sequences, since the increase in K really drives up the values of K to a power
at lightning speed. (Recall that 2^10 was about a thousand, 3^10 is about 59
thousand, and 4^10 is more than a million.)
Here's what a tribonnaci solution would look like, using the same principle of
saving our work as we go:
import java.util.HashMap;
import java.util.Map;
class Solution {
Map<Integer, Integer> tribonacciMap
= new HashMap<>();
public void setTribonacciMap() {
tribonacciMap.put(0, 0);
tribonacciMap.put(1, 1);
tribonacciMap.put(2, 1);
}
public int tribonacci(int n) {
setTribonacciMap();
if (n == 0 || n == 1 || n == 2) {
return tribonacciMap.get(n);
}
if (!tribonacciMap.containsKey(n))
{
tribonacciMap.put(n, (tribonacci(n -
1) + tribonacci(n - 2) + tribonacci(n - 3)));
}
return tribonacciMap.get(n);
}
}
No comments:
Post a Comment