순열, DFS
✅ 1부터 10 사이의 자연수 m개가 주어졌을 때, n개를 뽑을 수 있는 경우의 수를 모두 구하세요.
1
2
3
4
5
6
7
8
9
10
11
12
13
//⭐️input:
//자연수 개수 m, 뽑을 숫자 개수 n
//들어온 자연수
3 2
3 6 9
//⭐️output:
3 6
3 9
6 3
6 9
9 3
9 6
🔵 How to solve
🟢 Code
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
class Main {
static int n;
static int m;
static int[] intArr;
static int[] ch;
static int[] answer;
public void DFS(int L) {
if(L==m){
for(int x: answer){
System.out.print(x + " ");
}
System.out.println();
}else{
for(int i=0; i<n; i++){
if(ch[i] == 0) {
ch[i] = 1;
answer[L] = intArr[i]; //⭐️
DFS(L+1);
ch[i]=0; //체크 풀어주기
}
}
}
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
n= sc.nextInt();
m= sc.nextInt();
intArr= new int[n];
ch= new int[n];
answer= new int[m];
for(int i=0; i<n; i++){
intArr[i] = sc.nextInt();
}
T.DFS(0);
}
}
⭐️ What I learned
In this part, answer[L] = intArr[i]
I first made the code like answer[i] = intArr[i]
, and thus got a 🔴zero-exit error
.
it was because array answer only has up to n
size whereas i
is up to m
,
and since m
is bigger than n
, (m=3, n=2 in this case)
I got the 🔴zero-exit error
.
Then, my question was how to get to answer index
?!
The solution to this problem was using L
, which is the Level
that the DFS
is in right now,
which also matches the index
of the array.
This post is licensed under CC BY 4.0 by the author.