Description
You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.
Example 1:
Input: [4, 1, 8, 7] Output: True Explanation: (8-4) * (7-1) = 24 |
Example 2:
Input: [1, 2, 1, 2] Output: False |
Note:
The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2] , we cannot write this as 12 + 12.
Analysis
一共有4個數 + 4個運算符
Step 1:隨機挑選兩個數(考慮順序),共有12種情況
Step 2:爲這兩個排好序的數選擇操作,共有4種情況,計算得出結果
現在只有3個數 + 4個運算符
Step 3:隨機挑選兩個數(考慮順序),共有6種情況
Step 4:爲這兩個排好序的數選擇操作,共有4種情況,計算得出結果
現在只剩下2個數 + 4個運算符
Step 5:這兩個數排序,共有兩種情況
Step 6:爲這兩個排好序的數選擇操作,共有4種情況,計算得出結果
所以一共會有:
因爲Step1,3,5都要考慮到數字的順序,所以我決定使用一個可以輸出數字全排列的函數next_permutation(nums.begin(), nums.end())
(查資料)。使用這個函數,我們就不用考慮數字的排序了,只要考慮數字的組合和操作即可。
由於代碼很簡單,所以不做贅述。
Answer
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
//這個頭文件可以使abs函數參數變爲浮點數,也可直接使用fabs()
using namespace std;
class Solution {
public:
bool judgePoint24(vector<int>& nums) {
//由於要輸出全排序,要先將數字升序排好
sort(nums.begin(), nums.end());
do{
//注意一下下標必定從0開始不要犯這種錯誤
double a = nums[0], b = nums[1], c = nums[2], d = nums[3];
if (valid(a, b, c, d)) return true;
} while(next_permutation(nums.begin(), nums.end()));
return false;
}
private:
bool valid(double a, double b, double c, double d) {
if (valid(a + b, c, d) || valid(a - b, c, d) || valid(a * b, c, d) || (b && valid(a / b, c, d))) return true;
if (valid(a, b + c, d) || valid(a, b - c, d) || valid(a, b * c, d) || (c && valid(a, b / c, d))) return true;
if (valid(a, b, c + d) || valid(a, b, c - d) || valid(a, b, c * d) || (d && valid(a, b, c / d))) return true;
return false;
}
//要考慮到不能除0
bool valid(double a, double b, double c) {
if (valid(a + b, c) || valid(a - b, c) || valid(a * b, c) || (b && valid(a / b, c))) return true;
if (valid(a, b + c) || valid(a, b - c) || valid(a, b * c) || (c && valid(a, b / c))) return true;
return false;
}
/*爲什麼是小於0.0001呢,因爲double精度有限。有可能出現 2.0/3.0=0.666667,答案會有一點偏差*/
bool valid(double a, double b) {
if (abs(a + b - 24.0) < 0.0001 || abs(a - b - 24.0) < 0.0001 || abs(a * b - 24.0) < 0.0001 || (b && abs(a / b - 24.0) < 0.0001)) return true;
return false;
}
};