-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutation.java
More file actions
70 lines (64 loc) · 1.48 KB
/
permutation.java
File metadata and controls
70 lines (64 loc) · 1.48 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class permutation {
static int N, R;
static int numbers[], permutation[];
static boolean visited[];
public static void main(String[] args) throws IOException {
// input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken()); // numbers[]의 숫자 N개 중
R = Integer.parseInt(st.nextToken()); // R개를 뽑아서 나열한 순열
numbers = new int[N]; // N개의 숫자 저장
st = new StringTokenizer(br.readLine());
for(int i = 0; i < N; i++) {
numbers[i] = Integer.parseInt(st.nextToken());
}
visited = new boolean[N]; // 숫자를 뽑았는지 여부 체크
permutation = new int[R]; // 순열(결과) 저장
perm(0);
}
/**
* numbers[]의 숫자 n개 중 r개를 뽑아서 나열한 순열을 permutation[]에 저장
* cnt : 뽑은 개수
* */
private static void perm(int cnt) {
if(cnt == R) { // r개를 뽑았으면 출력
for(int x : permutation) {
System.out.print(x + " ");
}
System.out.println();
}
else {
for(int i = 0; i < N; i++) {
if(!visited[i]) {
permutation[cnt] = numbers[i];
visited[i] = true;
perm(cnt + 1);
visited[i] = false;
}
}
}
}
}
/*
input
4 2
1 2 3 4
output
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3
*/