Embercode
✕
Recursion and BacktrackingQuick quiz

Trees and memo

8 questions. Covers Memoised recursion.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <iostream> long long calls = 0; long long fib(int n) { ++calls; if (n < 2) return n; return fib(n - 1) + fib(n - 2); } int main() { std::cout << fib(5) << " " << calls << "\n"; } ``
  2. 2. What does this program print? ``cpp #include <iostream> long long calls = 0; long long ways(int n) { ++calls; if (n == 0) return 1; if (n < 0) return 0; return ways(n - 1) + ways(n - 2) + ways(n - 3); } int main() { long long a = ways(3); std::cout << "ways(3) = " << a << ", calls = " << calls << "\n"; } ``
  3. 3. What does this program print? ``cpp #include <iostream> #include <map> std::map<int, long long> memo; long long calls = 0; long long fib(int n) { ++calls; if (n < 2) return n; if (auto found = memo.find(n); found != memo.end()) return found->second; long long answer = fib(n - 1) + fib(n - 2); memo[n] = answer; return answer; } int main() { long long a = fib(10); std::cout << a << " calls=" << calls << " entries=" << memo.size() << "\n"; } ``
  4. 4. How many calls does naive Fibonacci make for input n, according to the recursion trees lesson?
  5. 5. After the memo is added, how does the number of calls for memoised fib(n) grow as n goes up?

5 question(s) left on this page.