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 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 calmum = new ArrayList();//计算结果存储区
                for(int k = 0;k 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 l = new ArrayList();
        for(int i = 0;i



你可能感兴趣的:(Leetcode)