문제
Combination Sum IV
Given an array of distinct integers nums
and a target integer target
, return the number of possible combinations that add up to target
.
The test cases are generated so that the answer can fit in a 32-bit integer.
Example 1:
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?
Solution
class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target+1];
dp[0] = 1;
for(int i=1;i<=target;i++) {
for(int num : nums) {
if(i>=num) {
dp[i]+=dp[i-num];
}
}
}
return dp[target];
}
}
시간 복잡도와 공간 복잡도
- 시간 복잡도:
- 외부 반복문:
target
까지 (O(target)
) - 내부 반복문:
nums
배열 길이 (O(n)
) - 총:
O(target * n)
- 외부 반복문:
- 공간 복잡도:
dp
배열 사용:O(target)
회고
dp[i]는 i를 만들 수 있는 조합의 수를 의미한다.
dp[i] = dp[i] + dp[i - num]
숫자 num을 선택하면, 남은 값은 i - num이 된다. 따라서, i - num을 만들 수 있는 조합의 수(dp[i - num])를 현재 i를 만들 수 있는 조합의 수에 추가한다.
'Algorithm > LeetCode' 카테고리의 다른 글
[DP] 91. Decode Ways (0) | 2024.12.01 |
---|---|
213. House Robber II (0) | 2024.11.30 |
1143. Longest Common Subsequence (0) | 2024.11.16 |
139. Word Break (0) | 2024.11.11 |
300. Longest Increasing Subsequence (0) | 2024.11.07 |