11import java .util .*;
2-
32class Solution {
4- List <Set <Integer >> candidateKeys = new ArrayList <>();
5-
3+ List <Set <Integer >> candidate = new ArrayList <>();
64 public int solution (String [][] relation ) {
7- int colCount = relation [0 ].length ;
8- boolean [] visited = new boolean [colCount ];
9-
10- for (int r = 1 ; r <= colCount ; r ++) { // 조합 크기 1~N
11- backtrack (0 , 0 , r , relation , visited );
5+
6+ for (int i = 1 ; i <= relation [0 ].length ; i ++) {
7+ back (i , 0 , 0 , relation , new boolean [relation [0 ].length ]);
128 }
13-
14- return candidateKeys .size ();
9+ return candidate .size ();
1510 }
16-
17- public void backtrack (int depth , int start , int target , String [][] relation , boolean [] visited ) {
18- if (depth == target ) {
11+
12+ public void back (int target , int start , int depth , String [][] relation , boolean [] visited ) {
13+
14+ if (depth == target ) {
1915 List <Integer > cols = new ArrayList <>();
20- for (int i = 0 ; i < visited .length ; i ++) {
21- if (visited [i ]) cols .add (i );
16+
17+ for (int i = 0 ; i < visited .length ; i ++) {
18+ if (visited [i ]) {
19+ cols .add (i );
20+ }
2221 }
23-
24- if (isUnique (cols , relation ) && isMinimal (cols )) {
25- candidateKeys .add (new HashSet <>(cols ));
26- }
27- return ;
22+ if (isUnique (cols , relation ) && isMin (cols )) {
23+ candidate .add (new HashSet <>(cols ));
24+ }
2825 }
29-
30- for (int i = start ; i < relation [0 ].length ; i ++) {
31- if (!visited [i ]) {
26+
27+
28+ for (int i = start ; i < relation [0 ].length ; i ++) {
29+ if (!visited [i ]) {
3230 visited [i ] = true ;
33- backtrack ( depth + 1 , i + 1 , target , relation , visited );
31+ back ( target , i + 1 , depth + 1 , relation , visited );
3432 visited [i ] = false ;
3533 }
3634 }
3735 }
38-
39- private boolean isUnique (List <Integer > cols , String [][] relation ) {
36+
37+ public boolean isUnique (List <Integer > cols , String [][] relation ) {
4038 Set <String > tuples = new HashSet <>();
41- for (String [] row : relation ) {
39+ for (String row [] : relation ) {
4240 StringBuilder sb = new StringBuilder ();
43- for (int c : cols ) sb .append (row [c ]).append ("|" );
41+ for (int nums : cols ) {
42+ sb .append (row [nums ]).append ("|" );
43+ }
4444 tuples .add (sb .toString ());
4545 }
4646 return tuples .size () == relation .length ;
47+
4748 }
48-
49- private boolean isMinimal (List <Integer > cols ) {
50- Set <Integer > current = new HashSet <>(cols );
51- for (Set <Integer > key : candidateKeys ) {
52- if (current .containsAll (key )) return false ;
49+
50+ public boolean isMin (List <Integer > cols ) {
51+ for (Set <Integer > can : candidate ) {
52+ Set <Integer > colsSet = new HashSet <>(cols );
53+
54+ if (colsSet .containsAll (can )) {
55+ return false ;
56+ }
5357 }
5458 return true ;
5559 }
56- }
60+ }
0 commit comments