the simplest thing is exhaustion, first enumerating the three-digit arrangement of 1-9 numbers, then adding operators to each arrangement, enumerating all suffix expressions, evaluating them, and finally de-duplicating them. This is the simplest and least efficient method.
then further consider the characteristics of the topic, you might as well specify that the first two digits of the found sequence of numbers should be calculated first, and then operate with the last bit. There is room for three digits to operate to get a result, and only two operations are needed. Considering the last operation, the last operation must be one of the four operations, so the goal is to enumerate a sequence of numbers whose length is 24
, whose length is 2 , and the second number of the sequence is one of the nine integers, and the first number is the result of the operation of two of the nine integers except the second one of the sequence.
for example, if the last operation is addition, then this is exhaustive
? + 1 = 24 => 23
? + 2 = 24 => 22
? + 3 = 24 => 21
...
? + 9 = 24 => 15
the last operation is subtraction, so it is exhaustive
? - 1 = 24 => 25
? - 2 = 24 => 26
? - 3 = 24 => 27
...
? - 9 = 24 => 33
the last operation is multiplication, so enumerate
? * 1 = 24 => 24.0
? * 2 = 24 => 12.0
? * 3 = 24 => 8.0
...
? * 9 = 24 => 2.666666666666667
the last operation is division, so enumerate
? / 1 = 24 => 24
? / 2 = 24 => 48
? / 3 = 24 => 72
...
? / 9 = 24 => 216
it can be noted that some results are impossible, such as 2169 = 24
. Even if repetition is allowed, 9 * 9
is at most 81
, so that the four operations of two different 1x9 integers cannot reach 21616
.
so we enumerate the possible results of the four operations of all two-digit 1 to 9 integers (some of which are impossible and can be pruned), continue to exhaustive, and we will get the results (there will be repetition)
? + ? = 23 => 1~917
...
? + ? = 17 => 1~917
? + 1 = 17 => 16 //
? + 2 = 17 => 15 //
...
? + 8 = 17 => 9 // 987(9+8)+7
? + 9 = 17 => 8 //
...
Finally, you have to repeat, or judge whether the currently exhausted sequences and operations are equivalent to the sequences and operations that have been obtained before, and just write this yourself.
24-point card algorithm is an example of the classic data structure and algorithm course. Search for more results. The above is just my temporary idea. At my level, this must not be the best solution (yes, I have never done this before)
skill is not as good as others, be willing to be outdone