您的位置:首页 > 其它

24 Game:组合运算

2017-12-26 17:54 253 查看
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.

思路:近两天心情不好,一切从简。回溯法穷举所有可能,把加减乘除操作中把产生的中间结果也作为元素参与穷举,这样就省略了最后对每个表达式进行解析的过程。

注意穷举的过程看做是有顺序的,因为 a / b 与 b / a 并不相同。

class Solution {
public boolean backtracking(List<Double> num){
if(num.size() < 1 ) return false;
if(num.size() == 1 ){
if(Math.abs( num.get(0) - 24 ) < 1e-6){
return true;
} else{
return false;
}
}
for(int i = 0;i<num.size();i++){//i,j 计算位
for(int j = 0;j<num.size();j++){
if(i == j) continue;
ArrayList<Double> calmum = new ArrayList<Double>();//计算结果存储区
for(int k = 0;k<num.size();k++){
if(k !=i && k!=j ) calmum.add(num.get(k));//添加剩余未被计算元素
}
for(int k=0;k<4;k++ ){//4种就算法则 + * - /
if(k < 2 && i > j) continue;//+ * 满足交换律,所以跳过重复运算
if(k == 0 ) calmum.add(num.get(i) + num.get(j));
if(k == 1 ) calmum.add(num.get(i) * num.get(j));
if(k == 2 ) calmum.add(num.get(i) - num.get(j));
if(k == 3 ) {
if(num.indexOf(j) == 0){
continue;
} else {
calmum.add(num.get(i) / num.get(j));
}
}
if(backtracking(calmum)) return true;
calmum.remove(calmum.size()-1);
}
}
}
return false;
}

public boolean judgePoint24(int[] nums) {
ArrayList<Double> l = new ArrayList<Double>();
for(int i = 0;i<nums.length;i++){
l.add((double) nums[i]);
}
return backtracking(l);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: