https://school.programmers.co.kr/learn/courses/30/lessons/42890
Level 2
프렌즈대학교 컴퓨터공학과 조교인 제이지는 네오 학과장님의 지시로, 학생들의 인적사항을 정리하는 업무를 담당하게 되었다.
그의 학부 시절 프로그래밍 경험을 되살려, 모든 인적사항을 데이터베이스에 넣기로 하였고, 이를 위해 정리를 하던 중에 후보키(Candidate Key)에 대한 고민이 필요하게 되었다.
후보키에 대한 내용이 잘 기억나지 않던 제이지는, 정확한 내용을 파악하기 위해 데이터베이스 관련 서적을 확인하여 아래와 같은 내용을 확인하였다.
제이지를 위해, 아래와 같은 학생들의 인적사항이 주어졌을 때, 후보 키의 최대 개수를 구하라.
import java.util.*;
class Solution {
List<Set<Integer>> candidateKeys = new ArrayList<>();
int colSize;
public int solution(String[][] relation) {
colSize = relation[0].length;
for (int i = 1; i <= colSize; i++) {
getCombinations(0, 0, i, new HashSet<>(), relation);
}
return candidateKeys.size();
}
private void getCombinations(int depth, int start, int r, Set<Integer> comb, String[][] relation) {
if (depth == r) {
if (isUnique(comb, relation) && isMinimal(comb)) {
candidateKeys.add(new HashSet<>(comb));
}
return;
}
for (int i = start; i < colSize; i++) {
comb.add(i);
getCombinations(depth + 1, i + 1, r, comb, relation);
comb.remove(i);
}
}
private boolean isUnique(Set<Integer> comb, String[][] relation) {
Set<String> tuples = new HashSet<>();
for (String[] row : relation) {
StringBuilder sb = new StringBuilder();
for (int idx : comb) {
sb.append(row[idx]).append(",");
}
tuples.add(sb.toString());
}
return tuples.size() == relation.length;
}
private boolean isMinimal(Set<Integer> comb) {
for (Set<Integer> key : candidateKeys) {
if (comb.containsAll(key)) return false;
}
return true;
}
}
getCombinations : 조합 생성
isUnique : 유일성 검사
row에서 조합된 값을 문자열로 만들어 Set에 넣고 중복 여부 확인isMinimal : 최소성 검사
