Pure backtracking solution,no loops


  • 0
    N

    public static List<String> readBinaryWatch(int num) {
    ArrayList<String> l = new ArrayList<String>();
    return readBinaryWatch(num, 0, 0, 0, 0,l);
    }

    public static List<String> readBinaryWatch(int num, int sumH, int sumM, int addH, int addM,ArrayList<String> l) {
    	if (num <= 0) {
    		String str =  sumH + ":";
    		if (sumM < 10)
    			str += "0" + sumM;
    		else
    			str += sumM;
    		l.add(str);
    	}
    	else{
    
    	if (addH < 1)
    		readBinaryWatch(num - 1, sumH + 1, sumM, addH + 1, addM,l);
    	if (addH < 3)
    		readBinaryWatch(num - 2, sumH + 2, sumM, addH + 2, addM,l);
    	if (addH < 7)
    		readBinaryWatch(num - 4, sumH + 4, sumM, addH + 4, addM,l);
    	if (addH < 15)
    		readBinaryWatch(num - 8, sumH + 8, sumM, addH + 8, addM,l);
    	if(addM<1)
    		readBinaryWatch(num-1,sumH,sumM+1,addH,addM+1,l);
    	if(addM<2)
    		readBinaryWatch(num-2,sumH,sumM+2,addH,addM+2,l);
    	if(addM<4)
    		readBinaryWatch(num-4,sumH,sumM+4,addH,addM+4,l);
    	if(addM<8)
    		readBinaryWatch(num-8,sumH,sumM+8,addH,addM+8,l);
    	if(addM<16)
    		readBinaryWatch(num-16,sumH,sumM+16,addH,addM+16,l);
    	if(addM<32)
    		readBinaryWatch(num-32,sumH,sumM+32,addH,addM+32,l);
    	
    	}
    	
    	return l;
    
    }

Log in to reply
 

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