티스토리 뷰
Problem
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
중복되지 않은 정수 배열과 타겟 정수가 주어질 때 더해서 타겟 정수가 되는 모든 조합의 개수를 구하는 문제입니다.
public class Solution {
public int combinationSum4(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] dp = new int[target + 1];
dp[0] = 1;
for (int i = 0; i < dp.length; i++) {
for (int num : nums) {
if (i + num <= target) {
dp[i + num] += dp[i];
}
}
}
return dp[target];
}
}
dp를 이용해 간단히 풀이할 수 있습니다.
Test
package io.lcalmsky.leetcode.combination_sum_iv;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
public void givenNumbers_whenFindCombination_thenCorrect() {
assertAll(
() -> test(new int[]{1, 2, 3}, 4, 7)
);
}
private void test(int[] given, int target, int expected) {
// when
Solution combinationSum4 = new Solution();
int actual = combinationSum4.combinationSum4(given, target);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
235. Lowest Common Ancestor of a Binary Search Tree (0) | 2022.08.12 |
---|---|
98. Validate Binary Search Tree (0) | 2022.08.11 |
729. My Calendar I (0) | 2022.08.05 |
890. Find and Replace Pattern (0) | 2022.07.30 |
34. Find First and Last Position of Element in Sorted Array (0) | 2022.07.29 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- JPA
- 알고리즘
- intellij
- 스프링 부트 튜토리얼
- Spring Data JPA
- Spring Boot Tutorial
- proto3
- 스프링 부트 애플리케이션
- 스프링부트
- 함께 자라기
- spring boot application
- gRPC
- JSON
- QueryDSL
- @ManyToOne
- Java
- leetcode
- Linux
- 스프링 데이터 jpa
- Spring Boot
- 스프링 부트 회원 가입
- 스프링 부트
- Jackson
- spring boot jwt
- 함께 자라기 후기
- r
- 클린 아키텍처
- Spring Boot JPA
- 헥사고날 아키텍처
- spring boot app
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함