39 Combination Sum
39 Combination Sum
문제
Given an array of distinct integers candidates and a target integer target,
return a list of all unique combinations of candidates where the chosen numbers sum to target.
You may return the combinations in any order.
- 서로 구별되는 후보 정수 배열과 타겟 정수를 받아서, 선택한 숫자의 합이 타겟 정수가 되는 유니크한 조합
The same number may be chosen from candidates an unlimited number of times.
Two combinations are unique if the frequency of at least one of the chosen numbers is different.
- 같은 수가 선택될 수 있다
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
조건
- $1 \le candidates.length \le 30$
- $1 \le candidates[i] \le 200$
- All elements of candidates are distinct.
- $1 \le target \le 500$
예제
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Input: candidates = [2], target = 1
Output: []
Input: candidates = [1], target = 1
Output: [[1]]
Input: candidates = [1], target = 2
Output: [[1,1]]
해결
1st
1 생각
- 조합 경우의 수를 뽑아서 합하는 것이라면 간단할 거 같지만…
- 같은 원소를 여러 번(무한히) 선택하여 사용할 수 있다는 점이 어려울 듯 하다
- 예제의 [2, 3, 6, 7]에서 7이 되도록 하기 위해 2를 두번 뽑았는데, 이를 어떻게 풀어야 할까?
- 아마 순서가 상관없으니 조합으로 되어 있지만, 같은 수가 또 뽑힐 수 있으니 순열도 고려해야 할 거 같다
- 전체 탐색하되, 77 조합처럼 pop()하지 말고, return 조건을
target
이거나target
을 넘는 경우로 보도록 하자