Input: nums = [1,2,3], target = 4
Output: 7
Explanation:
The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1)
Note that different sequences are counted as different combinations.
Example 2:
Input: nums = [9], target = 3
Output: 0
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 1000
All the elements of nums are unique.
1 <= target <= 1000
Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
classForgetfulList: def__init__(self, limit: int, default: int = None, cnt: int = 0): """Inits a forgetful list which can remember at most `limit` recent values. The first `cnt` values will be set to `default`. """ self._limit = limit self._buffer = [default] * limit self._pos = cnt % self._limit
classSolution: defcombinationSum4(self, nums: list[int], target: int) -> int: nums = [val for val in nums if val <= target] ifnot nums: return0
min_val = min(nums) max_val = max(nums) cw = ForgetfulList(max_val, 0, min_val) cw[0] = 1 for amt inrange(min_val, target + 1): cw.append(sum(cw[amt - val] for val in nums if amt >= val))