codekofi
← All problems

Problem 21

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. 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
4 int n = nums.size();
5
6 if (left == 0) {
7 out.push_back(current);
8 return;
9 }
10
11 if (left < 0 || i == n) {
12 return;
13 }
14
15 current.push_back(nums[i]);
16 build(nums, i, left - nums[i], current, out);
17 current.pop_back();
18
19 build(nums, i + 1, left, current, out);
20}
21
22vector<vector<int>> solution(const vector<int>& nums, int target) {
23
24 vector<vector<int>> ans;
25 vector<int> current;
26
27 build(nums, 0, target, current, ans);
28
29 return ans;
30}

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.