본문 바로가기

백준

BOJ[JAVA] 5568 카드놓기

https://www.acmicpc.net/problem/5568

 

5568번: 카드 놓기

예제 1의 경우 상근이는 11, 12, 21, 112, 121, 122, 212를 만들 수 있다.

www.acmicpc.net

 

import java.io.*;
import java.util.*;

public class Main {
	static int n, k;
	static int[] num, ans;
	static boolean[] check;
	static HashSet<String> set;
	
	public static void backtracking(int idx, int cnt) {
		check[idx] = true;
		ans[cnt-1] = num[idx];
		
		if(cnt == k) {
			String str="";
			for(int i=0;i<k;i++) {
				str = str.concat(Integer.toString(ans[i]));
			}
			set.add(str);
			return;
		}
		
		for(int i=0;i<n;i++) {
			if(!check[i]) {
				backtracking(i, cnt+1);
				check[i] = false;
			}
		}
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		n = Integer.parseInt(br.readLine());	// 카드 개수
		k = Integer.parseInt(br.readLine());	// 상근이가 선택한 카드 개수
		num = new int[n];	// 카드에 적혀있는 수 저장
		check = new boolean[n];  // 방문 여부 저장
		ans = new int[k];   // 나열한 수 저장
		
		for(int i=0;i<n;i++) {
			num[i] = Integer.parseInt(br.readLine());
		}
		
		set = new HashSet<String>();	// 만들 수 있는 정수 저장할 집합
		
		for(int i=0;i<n;i++) {
			Arrays.fill(check, false);
			backtracking(i, 1);
		}
		
		
		System.out.println(set.size());	// 만들 수 있는 정수 개수 출력
	}
}

'백준' 카테고리의 다른 글

BOJ[JAVA] 1182 부분수열의 합  (0) 2023.04.23
BOJ[JAVA] 17103 골드바흐 파티션  (0) 2023.04.23
BOJ[JAVA] 1929 소수 구하기  (1) 2023.04.16
BOJ[JAVA] 1448 삼각형 만들기  (0) 2023.04.09
BOJ[JAVA] 1874 스택수열  (0) 2023.04.09