|
| 1 | +# 377. Combination Sum IV |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Dynamic Programming. |
| 5 | +- Similar Questions: Combination Sum, Ways to Express an Integer as Sum of Powers. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given an array of **distinct** integers `nums` and a target integer `target`, return **the number of possible combinations that add up to** `target`. |
| 10 | + |
| 11 | +The test cases are generated so that the answer can fit in a **32-bit** integer. |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | +``` |
| 17 | +Input: nums = [1,2,3], target = 4 |
| 18 | +Output: 7 |
| 19 | +Explanation: |
| 20 | +The possible combination ways are: |
| 21 | +(1, 1, 1, 1) |
| 22 | +(1, 1, 2) |
| 23 | +(1, 2, 1) |
| 24 | +(1, 3) |
| 25 | +(2, 1, 1) |
| 26 | +(2, 2) |
| 27 | +(3, 1) |
| 28 | +Note that different sequences are counted as different combinations. |
| 29 | +``` |
| 30 | + |
| 31 | +Example 2: |
| 32 | + |
| 33 | +``` |
| 34 | +Input: nums = [9], target = 3 |
| 35 | +Output: 0 |
| 36 | +``` |
| 37 | + |
| 38 | + |
| 39 | +**Constraints:** |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +- `1 <= nums.length <= 200` |
| 44 | + |
| 45 | +- `1 <= nums[i] <= 1000` |
| 46 | + |
| 47 | +- All the elements of `nums` are **unique**. |
| 48 | + |
| 49 | +- `1 <= target <= 1000` |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +**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? |
| 54 | + |
| 55 | + |
| 56 | +## Solution |
| 57 | + |
| 58 | +```javascript |
| 59 | +/** |
| 60 | + * @param {number[]} nums |
| 61 | + * @param {number} target |
| 62 | + * @return {number} |
| 63 | + */ |
| 64 | +var combinationSum4 = function(nums, target, map = {}) { |
| 65 | + if (target === 0) return 1; |
| 66 | + if (map[target] !== undefined) return map[target]; |
| 67 | + var res = 0; |
| 68 | + for (var i = 0; i < nums.length; i++) { |
| 69 | + if (nums[i] > target) continue; |
| 70 | + res += combinationSum4(nums, target - nums[i], map); |
| 71 | + } |
| 72 | + map[target] = res; |
| 73 | + return res; |
| 74 | +}; |
| 75 | +``` |
| 76 | + |
| 77 | +**Explain:** |
| 78 | + |
| 79 | +Top-down dynamic programming. |
| 80 | + |
| 81 | +**Complexity:** |
| 82 | + |
| 83 | +* Time complexity : O(target). |
| 84 | +* Space complexity : O(target * n). |
0 commit comments