Recursion (Brute Force)
Intuition
Since order matters, this is a permutation-style counting problem. For each recursive call with a remaining target, we try every number in nums that does not exceed the target. If the target becomes zero, we have found one valid combination. The overlapping subproblems make this exponential without memoization.
Algorithm
- If `target == 0`, return `1` (one valid combination found).
- Initialize `count = 0`.
- For each number in `nums`, if `num <= target`, recursively count combinations for `target - num`.
- Return the total count.
O(n^target) where n is the length of numsSpaceO(target) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
if (target == 0) return 1;
int count = 0;
for (int num : nums) {
if (num <= target) {
count += combinationSum4(nums, target - num);
}
}
return count;
}
};class Solution {
public int combinationSum4(int[] nums, int target) {
if (target == 0) return 1;
int count = 0;
for (int num : nums) {
if (num <= target) {
count += combinationSum4(nums, target - num);
}
}
return count;
}
}from typing import List
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
if target == 0:
return 1
count = 0
for num in nums:
if num <= target:
count += self.combinationSum4(nums, target - num)
return countfunc combinationSum4(nums []int, target int) int {
if target == 0 {
return 1
}
count := 0
for _, num := range nums {
if num <= target {
count += combinationSum4(nums, target-num)
}
}
return count
}