|
| 1 | +const MAX_STRLEN = 8; |
| 2 | + |
| 3 | +const padString = (str, len) => { |
| 4 | + return Array.from({ length: len - str.length + 1 }).join("0") + str; |
| 5 | +}; |
| 6 | + |
1 | 7 | function solution(relation) { |
2 | 8 | const columns = relation[0].length; |
3 | 9 | const rows = relation.length; |
4 | | - const rset = new Set(); |
5 | 10 |
|
6 | 11 | const validate = (list) => { |
7 | 12 | const rset = new Set(); |
8 | 13 | const len = list.length; |
9 | | - |
10 | | - if (!len) return false; |
11 | 14 | for (let i = 0; i < rows; i++) { |
12 | | - const str = list.reduce((acc, cur) => { |
13 | | - let s = relation[i][cur]; |
14 | | - |
15 | | - return ( |
16 | | - acc + |
17 | | - s + |
18 | | - Array.from({ length: 8 - s.length }) |
19 | | - .map(() => "") |
20 | | - .join("0") |
21 | | - ); |
22 | | - }, ""); |
23 | | - |
24 | | - if (rset.has(str)) return false; |
25 | | - |
26 | | - rset.add(str); |
| 15 | + let temp = ""; |
| 16 | + for (let j = 0; j < len; j++) { |
| 17 | + if (list[j] === "1") temp += padString(relation[i][j], MAX_STRLEN); |
| 18 | + } |
| 19 | + if (rset.has(temp)) return false; |
| 20 | + rset.add(temp); |
27 | 21 | } |
28 | | - |
29 | 22 | return true; |
30 | 23 | }; |
31 | 24 |
|
32 | | - const idxList = Array.from({ length: columns }).map((_, i) => i); |
33 | | - const numSet = new Set(); |
34 | | - |
35 | | - const dfs = (list, rest) => { |
36 | | - numSet.add(list.sort((a, b) => a - b).join("")); |
37 | | - |
38 | | - rest.forEach((l, i) => { |
39 | | - const temp = rest.slice(); |
40 | | - temp.splice(i, 1); |
41 | | - dfs(list.concat([l]), temp); |
42 | | - }); |
43 | | - }; |
44 | | - |
45 | | - dfs([], idxList); |
46 | | - |
47 | 25 | const resultList = []; |
48 | 26 |
|
49 | | - Array.from(numSet).forEach((l) => { |
50 | | - const temp = l.split(""); |
| 27 | + const list = Array.from({ length: Math.pow(2, columns) - 1 }).map((_, i) => { |
| 28 | + const str = padString(parseInt(i + 1).toString(2), columns); |
51 | 29 |
|
52 | | - if (validate(temp)) { |
| 30 | + if (validate(str)) { |
53 | 31 | let go = true; |
54 | 32 | resultList.some((r) => { |
55 | | - if (l.indexOf(r) >= 0 || r.indexOf(l) >= 0) { |
| 33 | + const a = parseInt(r, 2); |
| 34 | + const b = parseInt(str, 2); |
| 35 | + const c = a | b; |
| 36 | + if (a === c || b === c) { |
56 | 37 | go = false; |
57 | 38 | return true; |
58 | 39 | } |
59 | 40 | }); |
60 | | - if (go) { |
61 | | - resultList.push(l); |
62 | | - } |
| 41 | + if (go) resultList.push(str); |
63 | 42 | } |
64 | 43 | }); |
65 | 44 |
|
|
0 commit comments