728x90
문제
서로 다른 n개의 원소들 중에서 r개만을 뽑아 일렬로 나열하는 것을 순열이라 한다. 예를 들어, 3개의 원소 a, b, c 중에서 2개만을 뽑아 나열하면 ab, ac, ba, bc, ca, cb 의 6가지 경우가 있다. n과 r이 주어질 때, n개의 소문자 중에서 r개만을 뽑아 나열하는 모든 경우를 출력하는 프로그램을 작성하시오. 단, a부터 시작하여 연속으로 n개의 알파벳을 갖고 있다고 하자.
입력
첫 번째 줄에 n과 r이 주어진다. ( 1 ≤ n ≤ 10, 0 ≤ r ≤ min(n, 7) )
출력
각 줄에 n개의 소문자 중에서 r개만을 뽑아 나열하는 경우를 사전순으로 나열한 결과를 출력한다.
예제 입력
4 2
예제 출력
ab
ac
ad
ba
bc
bd
ca
cb
cd
da
db
dc
// 코드
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
|
import java.util.*;
import java.io.*;
public class Main{
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int n;
static int m;
static int[] result;
static int[] visited;
static void getResult(int x) throws Exception {
if(x >= m) {
for(int i=0; i<m; i++) {
bw.write((char)result[i]);
}
bw.newLine();
} else {
for(int i=0; i<n; i++) {
if(visited[i] == 0) {
char alpha = 'a';
result[x] = alpha + i;
visited[i] = 1;
getResult(x+1);
visited[i] = 0;
}
}
}
}
public static void main(String[] args) throws Exception {
// Please Enter Your Code Here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
visited = new int[n];
result = new int[m];
getResult(0);
br.close();
bw.flush();
bw.close();
}
}
|
cs |
반응형