24 Game:组合运算

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:

  1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
  2. 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.
  3. 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);
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值