My backtracking java Solution.


  • 0
        ArrayList<String> result = new ArrayList<>();
        
    	public void core(int total, int cur, int[] leds, int curIndex,int oldIndex) {
    		if(curIndex > leds.length)
    			return;
    		if (cur == total) {
    			int tempH = 0;
    			StringBuffer hours = new StringBuffer();
    			// 先计算小时位
    			for (int i = 3; i >= 0; i--) {
    				if (leds[i] == 1) {
    					tempH += Math.pow(2, 3 - i);
    				}
    			}
    			if (tempH < 12) {
    				hours.append(tempH + ":");
    			}
    			// 再计算分钟位
    			int tempM = 0;
    			StringBuffer mins = new StringBuffer();
    			for (int i = 9; i >= 4; i--) {
    				if (leds[i] == 1) {
    					tempM += Math.pow(2, 9 - i);
    				}
    			}
    			if (tempM < 10) {
    				mins.append("0" + tempM);
    			} else if (tempM < 60) {
    				mins.append(tempM);
    			}
    			hours.append(mins);
    			if (tempH < 12 && tempM < 60) {
    				result.add(hours.toString());
    			}
    			if(oldIndex >=0 && oldIndex < leds.length)
    				leds[oldIndex] = 0;
    			return;
    		} else {
    			int i = curIndex;
    			while(i<10)
    			{
    				leds[i] = 1;
    				core(total, cur + 1, leds, i+1,i);
                    leds[i] = 0;
    				i++;
    			}
    			return;
    		}
    	}
        public List<String> readBinaryWatch(int num) {
    		if (num < 0)
    			return result;
    		int[] leds = new int[10];
    		core(num, 0, leds, 0,-1);
    		return result;        
        }
    }```

Log in to reply
 

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