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
|
public class test{
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
boolean[] visit = new boolean[5];
combination(visit, 5, 3, 0, arr);
}
private static void combination(boolean[] visit, int n, int r, int start, int[] arr) {
if (r == 0) {
for (int i = 0; i < visit.length; i++) {
if(visit[i]) System.out.print(arr[i]+" ");
}
System.out.println();
return;
}
for (int i = start; i < n; i++) {
visit[i] = true;
combination(visit, n, r - 1, i + 1, arr);
visit[i] = false;
}
}
}
1 3 5
1 3 7
1 3 9
1 5 7
1 5 9
1 7 9
3 5 7
3 5 9
3 7 9
5 7 9
|
cs |
조합
nCr n개 중 r개를 뽑음.
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
|
public class test{
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
int[] combArr = new int[3];
boolean[] visit = new boolean[5];
// combination(visit, 5, 3, 0, arr);
permutation(visit, 5, 3, arr, combArr, 0);
}
private static void permutation(boolean[] visit, int n, int r, int[] arr, int[] combArr, int index) {
if (r == index) {
for (int i = 0; i < 3; i++) {
System.out.print(combArr[i]+" ");
}
System.out.println();
return;
}
for (int i = 0; i < n; i++) {
if(visit[i]) continue;
combArr[index] = arr[i];
visit[i] = true;
permutation(visit, n, r, arr, combArr, index + 1);
visit[i] = false;
}
}
}
1 3 5 1 3 7 1 3 9 1 5 3 1 5 7 1 5 9 1 7 3 1 7 5 1 7 9 1 9 3 1 9 5 1 9 7
3 1 5 3 1 7 3 1 9 3 5 1 3 5 7 3 5 9 3 7 1 3 7 5 3 7 9 3 9 1 3 9 5 3 9 7
5 1 3 5 1 7 5 1 9 5 3 1 5 3 7 5 3 9 5 7 1 5 7 3 5 7 9 5 9 1 5 9 3 5 9 7
7 1 3 7 1 5 7 1 9 7 3 1 7 3 5 7 3 9 7 5 1 7 5 3 7 5 9 7 9 1 7 9 3 7 9 5
9 1 3 9 1 5 9 1 7 9 3 1 9 3 5 9 3 7 9 5 1 9 5 3 9 5 7 9 7 1 9 7 3 9 7 5
60
|
cs |
순서를 신경써가면서 뽑음 nPr
swap을 이용한 방법도 있음
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 | public class test{ public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; permutation2(arr, 0, 5, 3); } private static void permutation2(int[] arr, int depth, int n, int r) { if (depth == r) { for (int i = 0; i < r; i++) { System.out.print(arr[i]+" "); } System.out.println(); return; } for (int i = depth; i < n; i++) { swap(arr, depth, i); permutation2(arr, depth + 1, n, r); swap(arr, depth, i); } } private static void swap(int[] arr, int depth, int i) { int temp = arr[depth]; arr[depth] = arr[i]; arr[i] = temp; } } | cs |
'Java' 카테고리의 다른 글
Java String 메서드 정리 (계속해서 추가) (0) | 2020.08.25 |
---|---|
Java 우선순위 큐, Priority Queue (0) | 2020.08.21 |
Java 형변환 정리 (0) | 2020.08.19 |
Set 에 대하여 (0) | 2020.08.18 |
2020.04.08 자바 훑기 (String 클래스, StringBuilder 클래스, 각종 Collection) (1) | 2020.04.08 |