Skip to content

Commit b5b77c2

Browse files
add: combination sum
1 parent 68d4ab4 commit b5b77c2

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed

combination-sum/YoungSeok-Choi.java

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.Collections;
4+
import java.util.HashSet;
5+
import java.util.List;
6+
import java.util.Set;
7+
8+
// 시간복잡도: O(n ^ target)
9+
class Solution {
10+
11+
public List<Integer> tArr = new ArrayList<>();
12+
public Set<List<Integer>> s = new HashSet<>();
13+
14+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
15+
if(target == 1) {
16+
return new ArrayList<>();
17+
}
18+
19+
Arrays.sort(candidates);
20+
dfs(candidates, target, 0);
21+
22+
return new ArrayList<>(s);
23+
}
24+
25+
public void dfs(int[] candi, int target, int now) {
26+
27+
if(target < now) {
28+
return;
29+
}
30+
31+
// 정답 배열에 추가.
32+
if(target == now) {
33+
List<Integer> temp = new ArrayList<>(tArr);
34+
Collections.sort(temp);
35+
s.add(temp);
36+
return;
37+
}
38+
39+
for(int i = 0; i < candi.length; i++) {
40+
tArr.add(candi[i]);
41+
dfs(candi, target, (now + candi[i]));
42+
tArr.remove(tArr.size() - 1); // 가장 마지막 배열의 원소를 제거.
43+
}
44+
}
45+
}
46+
47+
48+
// NOTE: 세 수 이상의 조합의 합을 구하지 못하는 알고리즘.
49+
class WrongSolution {
50+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
51+
List<List<Integer>> res = new ArrayList<>();
52+
List<List<Integer>> result = new ArrayList<>();
53+
54+
if(target == 1) {
55+
return new ArrayList<>();
56+
}
57+
58+
Arrays.sort(candidates);
59+
60+
// i번째 값의 메모 구하기
61+
for(int i = 0; i < candidates.length; i++) {
62+
63+
// 0 ~ i - 1까지만 의 값으로 i번째 값끼리 답이 나는지 확인.
64+
for(int j = 0; j < i; j++) {
65+
int current = candidates[i];
66+
int before = candidates[j];
67+
68+
int start = 1;
69+
while(true) {
70+
71+
int startValue = current * start;
72+
if(startValue >= target) {
73+
break;
74+
}
75+
76+
List<Integer> ans = new ArrayList<>();
77+
78+
int diff = target - startValue;
79+
80+
if(diff % before == 0) {
81+
82+
for(int k = 0; k < start; k++) {
83+
ans.add(current);
84+
}
85+
86+
int temp = diff / before;
87+
for(int k = temp; k > 0; k--) {
88+
ans.add(before);
89+
}
90+
91+
res.add(ans);
92+
}
93+
94+
start++;
95+
}
96+
}
97+
98+
// i로만 답을 구하는 경우.
99+
int copy = target;
100+
List<Integer> ans = new ArrayList<>();
101+
if(target % candidates[i] == 0) {
102+
int mok = copy /= candidates[i];
103+
while(mok > 0) {
104+
ans.add(candidates[i]);
105+
mok--;
106+
}
107+
res.add(ans);
108+
}
109+
}
110+
111+
112+
for (int i = res.size() - 1; i >= 0; i--) {
113+
List<Integer> inner = new ArrayList<>(res.get(i));
114+
result.add(inner);
115+
}
116+
117+
return result;
118+
}
119+
}

0 commit comments

Comments
 (0)