/* Leet Code 39. Combination Sum Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. Example 2: Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]] Example 3: Input: candidates = [2], target = 1 Output: [] Example 4: Input: arr[] = [1, 2, 3], target = 5 Output: [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2], [2, 3]] You should state: “I think this is a classic backtracking with unlimited repetition problem — very similar to the coin change combinations problem.” Pseudo-code Idea Base cases: If target < 0 : not a valid combination so return back. If target == 0 : valid combination so store it as an answer. Recursive choices: At each step, we have two options for the current number: Pick the current element, reduce the target by arr[i] and call recursion with (i, target - arr[i]). Keeping the index unchanged allows us to reuse the current element until the target is either reached or exceeded. Skip the current element, move to the next index and call recursion with (i+1, target). Time Complexity: Exponential in worst case. * Roughly O(2^{target / min(candidates)}) or bounded by the number of combinations × average length. * Because of the constraint (<150 combinations) and small target (≤500), it runs efficiently in practice. * Each path in the recursion tree corresponds to a partial combination. Space Complexity: * O(target / min(cand)) for recursion depth (max length of combo). * Output space: O(number of combinations × average length) — guaranteed small. */ #include #include using namespace std; void print(const string& label, vector& v); void print(const string& label, vector>& v); class Solution { public: // Recursion / Backtracking — build combinations incrementally. void recurWithIndex(vector& input, vector>& result, size_t index, int remainingSum, vector& combinations) { string s; for (auto& i: combinations) s += to_string(i) + " "; string ss = combinations.size() == 0 ? "" : s; string input_idx = index < input.size() ? to_string(input[index]) : "NA"; cout << format(" combinations: {0:<10} index: {1} input[index]: {2:<3} remainingSum: {3}\n", ss, index, input_idx, remainingSum); if (remainingSum == 0) { result.emplace_back(combinations); cout << "\tresult: "; for (const auto& i: combinations) {cout << i << " ";} cout << endl; return; } if (remainingSum < 0) return; for (size_t i = index; i < input.size(); i++) { if (input[i] > remainingSum) // important optimization { //cout << format(" input[{}] == {} greater than remainingSum {} --> break\n", i, input[i], remainingSum); break; } combinations.push_back(input[i]); recurWithIndex(input, result, i, remainingSum - input[i], combinations); combinations.pop_back(); // backtrack } } vector> combinationSum(vector& input, int target) { vector> result; vector combinations; int index = 0; recurWithIndex(input, result, index, target, combinations); return result; } }; int main(void) { vector, int, vector>>> testCases = { // input target output { {2,3,6,7}, 7, {{2,2,3}, {7} }}, { {2,3,5}, 8, {{2,2,2,2},{2,3,3},{3,5}}}, { {2}, 1, {} }, { {1,2,3}, 5, {{1,1,1,1,1},{1,1,1,2},{1,1,3},{1,2,2},{2,3}}}, }; for (const auto& testCase: testCases) { Solution s; vector input = get<0>(testCase); int target = get<1>(testCase); vector> expected = get<2>(testCase); cout << "input: {"; for (auto& i: input) cout << i << ","; cout << "} " << "target: " << get<1>(testCase) << endl; vector> result = s.combinationSum(input, target); print("result:", result); EXPECT_EQ(expected, result); cout << setfill('-') << setw(30) << "-" << setfill(' ') << endl; } return 0; } void print(const string& label, vector& v) { string s(label + " ["); for (auto& i: v) s += to_string(i) + ","; s += "] "; cout << s << endl; } void print(const string& label, vector>& v) { cout << label <<" ["; for (size_t i = 0; i < v.size(); i++) { cout << "["; for (size_t j = 0; j < v.at(i).size(); j++) { cout << v.at(i).at(j) << ","; } cout << "]"; } cout << "]\n"; }