-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
679. 24 Game #307
Labels
Comments
Solution
/**
* @param {number[]} nums
* @return {boolean}
*/
var judgePoint24 = function(nums) {
let result = false;
const operators = ['+', '-', '*', '/'];
backtracking(nums);
return result;
function backtracking(nums) {
if (result) {
return;
}
if (nums.length === 1) {
result = Math.abs(nums[0] - 24) < 0.0000001;
return;
}
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (i === j) {
continue;
}
for (let s = 0; s < operators.length; s++) {
if (i < j) {
backtracking([
...nums.slice(0, i),
...nums.slice(i + 1, j),
...nums.slice(j + 1),
calc(nums[i], nums[j], operators[s])
]);
} else {
backtracking([
...nums.slice(0, j),
...nums.slice(j + 1, i),
...nums.slice(i + 1),
calc(nums[i], nums[j], operators[s])
]);
}
}
}
}
}
function calc(a, b, operator) {
switch(operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
}
};
function judgePoint24(nums: number[]): boolean {
let result = false;
const operators: ['+', '-', '*', '/'] = ['+', '-', '*', '/'];
backtracking(nums);
return result;
function backtracking(nums: number[]) {
if (result) {
return;
}
if (nums.length === 1) {
result = Math.abs(nums[0] - 24) < 0.0000001;
return;
}
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (i === j) {
continue;
}
for (let s = 0; s < operators.length; s++) {
if (i < j) {
backtracking([
...nums.slice(0, i),
...nums.slice(i + 1, j),
...nums.slice(j + 1),
calc(nums[i], nums[j], operators[s])
]);
} else {
backtracking([
...nums.slice(0, j),
...nums.slice(j + 1, i),
...nums.slice(i + 1),
calc(nums[i], nums[j], operators[s])
]);
}
}
}
}
}
function calc(a: number, b: number, operator: '+' | '-' | '*' | '/') {
switch(operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
}
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
679. 24 Game
你有 4 张写有 1 到 9 数字的牌。你需要判断是否能通过
*
,/
,+
,-
,(
,)
的运算得到 24。Example 1
Example 2
Note
The text was updated successfully, but these errors were encountered: