|
1 | 1 | package p06xx
|
2 | 2 |
|
3 | | -import kotlin.math.absoluteValue |
4 | 3 | import util.expect
|
| 4 | +import kotlin.math.absoluteValue |
5 | 5 |
|
6 | 6 | fun main() {
|
7 | 7 | class Solution {
|
8 | 8 | fun judgePoint24(cards: IntArray): Boolean {
|
9 | | - val dp = Array(0b1111) { |
10 | | - hashSetOf<Double>() |
| 9 | + val dp = Array(1 shl 4) { hashSetOf<Double>() } |
| 10 | + repeat(4) { |
| 11 | + dp[1 shl it] += cards[it].toDouble() |
11 | 12 | }
|
12 | 13 |
|
13 | | - fun join(set1: Set<Double>?, set2: Set<Double>?): Set<Double> { |
14 | | - val res = hashSetOf<Double>() |
15 | | - |
16 | | - set1?.forEach { s1 -> |
17 | | - set2?.forEach { s2 -> |
18 | | - res.add(s1 + s2) |
19 | | - res.add(s1 - s2) |
20 | | - res.add(s2 - s1) |
21 | | - res.add(s1 * s2) |
22 | | - res.add(s1 / s2) |
23 | | - res.add(s2 / s1) |
24 | | - } |
25 | | - } |
26 | | - |
27 | | - return res |
28 | | - } |
29 | | - |
30 | | - repeat(0b1111) { num -> |
31 | | - repeat(4) { d -> |
32 | | - if (num and (1 shl d) > 0) { |
33 | | - val target = num - (1 shl d) |
34 | | - |
35 | | - if (target == 0) { |
36 | | - dp[num].add(cards[d].toDouble()) |
37 | | - } else { |
38 | | - dp[num].addAll(join(dp[1 shl d], dp[target])) |
| 14 | + repeat(16) { |
| 15 | + for (p in 1..it / 2) { |
| 16 | + if (p and it == p) { |
| 17 | + dp[p].forEach { s1 -> |
| 18 | + dp[it - p].forEach { s2 -> |
| 19 | + dp[it].add(s1 + s2) |
| 20 | + dp[it].add(s1 - s2) |
| 21 | + dp[it].add(s2 - s1) |
| 22 | + dp[it].add(s1 * s2) |
| 23 | + dp[it].add(s1 / s2) |
| 24 | + dp[it].add(s2 / s1) |
| 25 | + } |
39 | 26 | }
|
40 | 27 | }
|
41 | 28 | }
|
42 | 29 | }
|
43 | 30 |
|
44 | | - return arrayOf( |
45 | | - 0b0001 to 0b1110, |
46 | | - 0b0010 to 0b1101, |
47 | | - 0b0100 to 0b1011, |
48 | | - 0b1000 to 0b0111, |
49 | | - 0b0011 to 0b1100, |
50 | | - 0b0101 to 0b1010, |
51 | | - 0b1001 to 0b0110 |
52 | | - ).any { (l, r) -> |
53 | | - join(dp[l], dp[r]).any { |
54 | | - (it - 24.0).absoluteValue < 0.000001 |
55 | | - } |
56 | | - } |
| 31 | + return dp[0b1111].any { (it - 24).absoluteValue < .0000001 } |
57 | 32 | }
|
58 | 33 | }
|
59 | 34 |
|
|
0 commit comments