Java Brute Force II


  • 0

    Combine 1..n element randomly first, and see if the rest can be a right candidate(the same way)

    class Solution {
        public boolean judgePoint24(int[] nums) {
            return judge(nums, 24.0, 0);
        }
        
        public boolean judge(int[] nums, double target, double temp) {
            int n = nums.length;
        	if(target == 0 && n > 0) {
        		return false;
        	}
            if(n == 0) {
            	if(Math.abs(target - temp) <= 0.00001)
            		return true;
            	return false;
            }
            for(int i = 0; i < n; ++i) {
                int cur = nums[i];
                int[] curNs = new int[n-1];
                int p = 0;
                for(int j = 0;j < n; ++j){
                    if(j==i)
                        continue;
                    curNs[p++] = nums[j];
                }
                if(temp!=0) {
                	List<Double> cL = getPossible(cur, temp);
                	for(double c:cL) {
    	                if(judge(curNs, target, c) || judge(curNs, target-c, 0) || judge(curNs, target+c, 0) 
                            || judge(curNs, c-target, 0) || (c!=0 && judge(curNs, target/c, 0)) 
                            || (c!=0 && judge(curNs, c/target, 0)) || (c!=0 && judge(curNs, c*target, 0))) {
    	                	return true;
    	                }            	
                	}
                } else {
                	if(judge(curNs, target, cur) || judge(curNs, target-cur, 0) || judge(curNs, target+cur, 0) 
                            || judge(curNs, cur-target, 0) || (cur!=0 && judge(curNs, target/cur, 0)) 
                            || (cur!=0 && judge(curNs, cur/target, 0)) || (cur!=0 && judge(curNs, cur*target, 0))) {
                		return true;
                	}
                }
            }
            return false;
        }
        
        private static List<Double> getPossible(double x, double y) {
            List<Double> l = new ArrayList<Double>();
            l.add(x + y);
            l.add(x - y);
            l.add(y-x);
            l.add(x*y);
            l.add(x/y);
            l.add(y/x);
            return l;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.