Java very easy to understand solution !


  • 0
    D
    class Solution {
    	public static boolean judgePoint24(int[] nums) {
    		List<int[]> list = new ArrayList();
    		getPermutations(list, nums, 0, nums.length - 1);
    		for (int[] l : list) {
    			Set<Double> st = calculate(l, 0, l.length - 1);
    			System.out.println(st);
    			for (Double d : st) {
    			if (Math.abs(d - 24.0) < 0.001)
    				return true;
    			}
    		}
    		return false;
    	}
    
    	public static void getPermutations(List<int[]> list, int[] arr, int s, int e) {
    		if (s > e) {
    			list.add(arr.clone());
    		}
    		for (int i = s; i <= e; i++) {
    			swap(arr, s, i);
    			getPermutations(list, arr, s + 1, e);
    			swap(arr, s, i);
    		}
    	}
    
    	public static void swap(int[] arr, int i, int j) {
    		int tmp = arr[j];
    		arr[j] = arr[i];
    		arr[i] = tmp;
    	}
    
    	public static Set<Double> calculate(int[] arr, int s, int e) {
    		Set<Double> st = new HashSet();
    		if (s == e) {
    			st.add((double) arr[s]);
    			return st;
    		}
    		for (int i = s; i < e; i++) {
    			Set<Double> a = calculate(arr, s, i);
    			Set<Double> b = calculate(arr, i + 1, e);
    			for (Double ia : a) {
    				for (Double ib : b) {
    					st.add(ia * ib);
    					st.add(ia - ib);
    					st.add(ia + ib);
    					if (ib != 0)
    						st.add(ia / ib);
    				}
    			}
    		}
    		return st;
    	}
    }
    
    

Log in to reply
 

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