Skip to content

Commit 0ac5475

Browse files
author
jinvicky
committed
combination sum solution
1 parent af85fa8 commit 0ac5475

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
class Solution {
5+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
6+
List<List<Integer>> answer = new ArrayList<>();
7+
8+
makeCombination(candidates, target, 0, new ArrayList<>(), 0, answer);
9+
return answer;
10+
}
11+
12+
private void makeCombination(int[] candidates,
13+
int target,
14+
int idx,
15+
List<Integer> comb,
16+
int total,
17+
List<List<Integer>> res) {
18+
if (total == target) {
19+
res.add(new ArrayList<>(comb));
20+
return;
21+
}
22+
23+
if (total > target || idx >= candidates.length) {
24+
return;
25+
}
26+
27+
comb.add(candidates[idx]);
28+
makeCombination(candidates, target, idx, comb, total + candidates[idx], res);
29+
comb.remove(comb.size() - 1);
30+
makeCombination(candidates, target, idx + 1, comb, total, res);
31+
}
32+
}

โ€Žnumber-of-1-bits/jinvicky.javaโ€Ž

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
class Solution {
22
// [sol1] ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด์„œ ((n>>i) & 1) == 1๋ฅผ ๋งŒ์กฑํ•˜๋Š” ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค.
3+
// n์„ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š์ง€๋งŒ [sol1-1]๋ณด๋‹ค ๋А๋ฆฌ๋‹ค.
34
public int hammingWeight(int n) {
45
int answer = 0;
56
for(int i = 0; i < 32; i++) {
@@ -11,8 +12,29 @@ public int hammingWeight(int n) {
1112
return answer;
1213
}
1314

15+
// [sol1-1] n ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜๋ฉด์„œ [sol1]๋ณด๋‹ค ์„ฑ๋Šฅ์ด ๊ฐœ์„ ๋œ๋‹ค.
16+
public int hammingWeight1_1(int n) {
17+
int answer = 0;
18+
for (int i = 0; i < 32; i++) {
19+
answer += (n & 1);
20+
n >>>= 1;
21+
}
22+
return answer;
23+
}
24+
1425
// [sol2] ์ž๋ฐ”๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด 1๊ฐœ์˜ ๋ฉ”์„œ๋“œ, 1์ค„์˜ ์ฝ”๋“œ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.
1526
public int hammingWeight2 (int n) {
1627
return Integer.bitCount(n);
1728
}
29+
30+
// [sol3] 1์˜ ๊ฐœ์ˆ˜๋งŒํผ๋งŒ ๋ฐ˜๋ณตํ•œ๋‹ค.
31+
// ์˜ˆ) n = 1011 -> 1000 -> 0000 ์ข…๋ฃŒ
32+
public int hammingWeight3(int n) {
33+
int answer = 0;
34+
while (n != 0) {
35+
n &= (n - 1); // ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ 1 ๋น„ํŠธ๋ฅผ 0์œผ๋กœ ๋งŒ๋“ฆ
36+
answer++;
37+
}
38+
return answer;
39+
}
1840
}

0 commit comments

Comments
ย (0)