8 questions. Covers Debugging lab: DP bugs.
Questions 1 to 5 of 8
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]; }
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]; } }
cpp // Fewest coins that make
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];
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'; }
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.