Skip to content

Commit 0babf3d

Browse files
committed
Add combination code
1 parent d918589 commit 0babf3d

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed
Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,43 @@
11
package algorithm.basicMath;
22

3-
/**
4-
* Created by Jbee on 2017. 6. 5..
5-
*/
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.CoreMatchers.is;
6+
import static org.junit.Assert.assertThat;
7+
68
public class BasicCombination {
9+
10+
/*
11+
TASK
12+
n개의 서로 다른 원소 중 r개의 원소를 순서없이 선택하는 방법의 수를 구한다.
13+
*/
14+
15+
@Test
16+
public void test() {
17+
assertThat(getByRecursion(0, 0), is(1));
18+
assertThat(getByRecursion(1, 0), is(1));
19+
assertThat(getByRecursion(2, 1), is(2));
20+
assertThat(getByRecursion(8, 3), is(56));
21+
22+
assertThat(getByDp(0, 0), is(1));
23+
assertThat(getByDp(1, 0), is(1));
24+
assertThat(getByDp(2, 1), is(2));
25+
assertThat(getByDp(8, 3), is(56));
26+
}
27+
28+
public int getByRecursion(int n, int r) {
29+
if (r == 0 || n == r) {
30+
return 1;
31+
}
32+
return getByRecursion(n - 1, r - 1) + getByRecursion(n - 1, r);
33+
}
34+
35+
public int getByDp(int n, int r) {
36+
int cache[][] = new int[10][10];
37+
if (r == 0 || n == r) {
38+
return 1;
39+
}
40+
if (cache[n][r] != 0) return cache[n][r];
41+
return cache[n][r] = getByDp(n - 1, r - 1) + getByDp(n - 1, r);
42+
}
743
}

0 commit comments

Comments
 (0)