codekofi
← All problems

Problem 143

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 grow(const vector<int>& nums, int i, int left,
2 vector<int>& current, vector<vector<int>>& out) {
3
4 if (left == 0) {
5 out.push_back(current);
6 return;
7 }
8
9 int n = nums.size();
10
11 for (int j = i; j < n; j++) {
12
13 if (j > i && nums[j] == nums[j - 1]) {
14 continue;
15 }
16
17 if (nums[j] > left) {
18 break;
19 }
20
21 current.push_back(nums[j]);
22 grow(nums, j + 1, left - nums[j], current, out);
23 current.pop_back();
24 }
25}
26
27vector<vector<int>> solution(vector<int> nums, int target) {
28
29 sort(nums.begin(), nums.end());
30
31 vector<vector<int>> ans;
32 vector<int> current;
33
34 grow(nums, 0, target, current, ans);
35
36 return ans;
37}

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.