-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathforest000014.java
41 lines (33 loc) ยท 1.43 KB
/
forest000014.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
time complexity: O(nlogn)
- nums ๋ฐฐ์ด(=candidates) ์ ๋ ฌ: O(nlogn)
- ์ฌ๊ท ํธ์ถ ๋ถ๋ถ์ ์๊ฐ ๋ณต์ก๋๋ฅผ ๊ณ์ฐํ๊ธฐ๊ฐ ์ด๋ ต๋ค์.. candidates ๋ฐฐ์ด์ ์ ๋ ฌํด๋์ด์, target๊น์ง ๋จ์ ์ฐจ์ด๊ฐ ํ์ฌ ํ์ธํ๊ณ ์๋ candidate๋ณด๋ค ์๋ค๋ฉด ๋ฃจํ๋ฅผ ๋น ์ ธ๋์ค๊ฒ ํด์ O(n^t)๋ณด๋ค๋ ์์ ํ
๋ฐ, ์ด๋ฐ ๊ฒฝ์ฐ์๋ ์ด๋ป๊ฒ ํํํด์ผ ์ ์ ํ์ง ์ ๋ชจ๋ฅด๊ฒ ์ต๋๋ค.
space complexity: O(1) - ์ ๋ต์ผ๋ก ์ฌ์ฉํ ์ด์ค List๋ ์ ์ธ
*/
class Solution {
ArrayList<Integer> nums;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
nums = Arrays.stream(candidates)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
Collections.sort(nums);
return calc(target, 0);
}
private List<List<Integer>> calc(int target, int curr) {
if (target == 0) {
ArrayList<List<Integer>> lists = new ArrayList<>();
lists.add(new ArrayList<>());
return lists;
}
List<List<Integer>> ret = new ArrayList<>();
boolean found = false;
for (int i = curr; i < nums.size() && nums.get(i) <= target; i++) {
List<List<Integer>> results = calc(target - nums.get(i), i);
for (List<Integer> result : results) {
result.add(nums.get(i));
ret.add(result);
}
}
return ret;
}
}