Java, recursive version, clean.


  • 0
    N
    public class Solution {
        public List<String> readBinaryWatch(int num) {
            List<String> ans = new ArrayList<>();
            bt(ans, num, 0, 0);
            return ans;
        }
        
        private void bt(List<String> ans, int num, int start, int bit){
            if(num == 0){
                int minutes = 0;
                int hour = 0;
                int curNum = 1;
                for(int i=0; i<10; i++){
                    if(i < 6){
                        minutes += ((bit>>i)&1)*curNum;
                    }else{
                        hour += ((bit>>i)&1)*curNum/64;
                    }
                    curNum *= 2;
                }
                if(hour < 12 && minutes < 60){
                        ans.add(hour+":" + (minutes<10 ? "0"+minutes : minutes));
                }
                return;
            }
            
            for(int i=start; i<10; i++){
                if(((bit >> i) & 1 )!= 1){
                    bt(ans, num-1, i+1, bit | (1<<i));
                }
            }
        }
    }
    

Log in to reply
 

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