문제
https://www.acmicpc.net/problem/5568
5568번: 카드 놓기
예제 1의 경우 상근이는 11, 12, 21, 112, 121, 122, 212를 만들 수 있다.
www.acmicpc.net
import java.util.HashSet;
import java.util.Scanner;
public class Main5568_1 {
static int N;
static int k;
static int[] n;
static int[] arr;
static boolean[] visit;
static HashSet<String> ans = new HashSet<String>();
public static void compare(int cnt) {
String no = "";
if (cnt == k) {
for (int i=0; i<arr.length; i++) {
no += arr[i];
}
ans.add(no);
} else {
for (int i=0; i<N; i++) {
if (!visit[i]) {
arr[cnt] = n[i];
visit[i] = true;
compare(cnt+1);
visit[i] = false;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
k = sc.nextInt();
n = new int[N];
arr = new int[k];
visit = new boolean[N];
for (int i=0; i<N; i++) {
n[i] = sc.nextInt();
}
sc.close();
compare(0);
System.out.println(ans.size());
}
}
1. 정답
2. 이제 어느정도 완전탐색류의 문제는 적응이 된듯하다. 다만 세부적으로 들어가면 아직 코드가 미숙한 부분들이 있으니 조금씩 바꿔나가보자
백준 5568 카드 놓기 문제풀이 (JAVA)
카드를 뽑았을 때 모든 경우의 수를 전부 계산한다. 물론, 전부 계산하면 중복된 값이 발생하기 때문에 HashSet에다가 넣어주면 중복된 값은 입력되지 않는다! 재귀함수를 이용하여, 아직 뽑지 않
velog.io
해당 문제를 나와 비슷한 방식으로 접근하나 매개변수를 추가함으로써 코드를 더 단순화 시켰다. 큰 차이는 없겠지만 항상 코드를 직관적이고 단순화하는 방법에 대해 끊임없는 고민을 해야겠다.
'백준' 카테고리의 다른 글
백준 17626번 ☆ (0) | 2022.11.19 |
---|---|
백준 2503번 ☆ (0) | 2022.11.18 |
백준 2422번 (0) | 2022.11.16 |
백준 2661번 ☆ (0) | 2022.11.15 |
백준 1969번 ☆ (0) | 2022.11.15 |