Embercode
✕
Dynamic ProgrammingQuick quiz

DP bug hunt

8 questions. Covers Debugging lab: DP bugs.

Questions 1 to 5 of 8

  1. 1. The function should return 4 for n = 3, but it returns 3. What is the bug? ``cpp // Ways to climb n steps, taking 1, 2 or 3 steps at a time long long climb(int n) { std::vector<long long> ways(n + 1, 0); ways[0] = 0; ways[1] = 1; ways[2] = 2; for (int i = 3; i <= n; ++i) { ways[i] = ways[i - 1] + ways[i - 2] + ways[i - 3]; } return ways[n]; } ``
  2. 2. Which part of this code gives wrong counts? ``cpp // Paths from the top-left to the bottom-right corner, moving right or down std::vector<std::vector<long long>> ways(rows, std::vector<long long>(cols, 1)); for (int r = 1; r < rows; ++r) { for (int c = cols - 1; c >= 1; --c) { ways[r][c] = ways[r - 1][c] + ways[r][c - 1]; } } ``
  3. 3. Which bug is in this function? ``cpp // Fewest coins that make amount std::vector<int> fewest(amount + 1, 0); // 0 means 'not reached' for (int a = 1; a <= amount; ++a) { int best = 0; for (int c : coins) { if (c <= a && (best == 0 || fewest[a - c] + 1 < best)) { best = fewest[a - c] + 1; } } fewest[a] = best; } return fewest[amount]; ``
  4. 4. What happens when this program runs? ``cpp #include <iostream> #include <vector> int main() { int n = 3; std::vector<long long> ways(n + 1, 0); ways[0] = 1; ways[1] = 1; for (int i = 0; i <= n; ++i) { ways.at(i) = ways.at(i - 1) + ways.at(i - 2); } std::cout << ways.at(n) << '\n'; } ``
  5. 5. What does this program print? ``cpp #include <iostream> #include <vector> int main() { const int rows = 2; const int cols = 4; std::vector<long long> row(cols, 1); for (int r = 1; r < rows; ++r) { for (int c = cols - 1; c >= 1; --c) { row[c] += row[c - 1]; } } std::cout << row[cols - 1] << '\n'; } ``

5 question(s) left on this page.