1. Recursive DFS Permutation Search
Intuition
At each step, subtract each candidate number from remaining target and sum all valid paths.
Algorithm
- Define
dfs(rem). - If
rem == 0, return 1. - If
rem < 0, return 0. - Initialize
total = 0. - For each
xinnums:total += dfs(rem - x). - Return
total.
#include <iostream>#include <vector> using namespace std; int dfs(int rem, const vector<int>& nums) { if (rem == 0) return 1; if (rem < 0) return 0; int count = 0; for (int x : nums) { count += dfs(rem - x, nums); } return count;} int combinationSum4Rec(vector<int>& nums, int target) { return dfs(target, nums);} int main() { vector<int> nums = {1, 2, 3}; int target = 4; cout << "Combinations (Recursive): " << combinationSum4Rec(nums, target) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^target) where N = nums.length - Space complexity:
O(target) recursion stack