codekofi
← All problems

Problem 21

Medium40 XP

1 · Worked examples

0 / 3

Give it an input and say what you think comes back. It compiles and runs for real, so a wrong guess still shows you the answer — probe as much as you like. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1void build(const vector<int>& nums, int i, int left,
2 vector<int>& current, vector<vector<int>>& out) {
3 int n = nums.size();
4 if (left == 0) {
5 out.push_back(current);
6 return;
7 }
8 if (left < 0 || i == n) return;
9
10 current.push_back(nums[i]);
11 build(nums, i, left - nums[i], current, out);
12 current.pop_back();
13
14 build(nums, i + 1, left, current, out);
15}
16
17vector<vector<int>> solution(const vector<int>& nums, int target) {
18 vector<vector<int>> out;
19 vector<int> current;
20 build(nums, 0, target, current, out);
21 return out;
22}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.