1. Binary Choice State Recursion (Pick vs Not Pick)
Intuition
Define solve(index, target, current). Base case: if index == n, check if target == 0 and record solution. Recursive branches: (1) Pick branch: if candidates[index] <= target, push candidate and call solve(index, target - candidates[index], current). (2) Don't Pick branch: pop candidate and call solve(index + 1, target, current).
When to apply: Great for conceptual clarity and constructing recursion trees directly.
Algorithm
- Base case 1: If
index == candidates.length, iftarget == 0add copy ofcurrenttoresult; return. - Pick choice: If
candidates[index] <= target, pushcandidates[index], callsolve(index, target - candidates[index]), and popcandidates[index]. - Not-Pick choice: Call
solve(index + 1, target).
#include <iostream>#include <vector> using namespace std; class Solution { void solve(int index, int target, vector<int>& candidates, vector<int>& current, vector<vector<int>>& result) { if (index == candidates.size()) { if (target == 0) { result.push_back(current); } return; } // Choice 1: Pick if (candidates[index] <= target) { current.push_back(candidates[index]); solve(index, target - candidates[index], candidates, current, result); current.pop_back(); // backtrack } // Choice 2: Don't Pick solve(index + 1, target, candidates, current, result); } public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> result; vector<int> current; solve(0, target, candidates, current, result); return result; }}; int main() { Solution sol; vector<int> candidates = {2, 3, 6, 7}; int target = 7; auto res = sol.combinationSum(candidates, target); for (const auto& comb : res) { cout << "[ "; for (int v : comb) cout << v << " "; cout << "] "; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^T * K)— T is target value. In worst case (smallest candidate = 2), tree depth is T/2. K is average length of each combination copied. - Space complexity:
O(T / min_val)— Maximum recursion depth is target / min(candidates) frames.