Challenge: Make the Target
Completed
Given distinct positive numbers (numbers may be reused) and a target, print every combination that adds up to the target in non-decreasing order, joined with +, in the order backtracking finds them with sorted numbers. Then print Ways: <count>.
Input
Line 1: n target (target ≤ 40). Line 2: n distinct positive numbers.
Output
The combinations, then the count.
Example
Input
4 7 2 3 6 7
Output
2+2+3 7 Ways: 2
Editor
C++
Hints
Sort first.
Recurse with i (not i + 1) so a number can repeat.
Break when nums[i] > left.
Solution explanation
Starting each loop at start keeps combinations in order, so none appears twice.
Show solution
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
vector<int> nums, cur;
int ways = 0;
void explore(int start, int left) {
if (left == 0) {
for (size_t i = 0; i < cur.size(); i++) cout << cur[i] << (i + 1 < cur.size() ? "+" : "\n");
ways++;
return;
}
for (int i = start; i < (int)nums.size(); i++) {
if (nums[i] > left) break;
cur.push_back(nums[i]);
explore(i, left - nums[i]);
cur.pop_back();
}
}
int main() {
int n, target;
cin >> n >> target;
nums.resize(n);
for (int& x : nums) cin >> x;
sort(nums.begin(), nums.end());
explore(0, target);
cout << "Ways: " << ways << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module