Simple Backtracking Java Solution


  • 0
    public class Solution {
        public List<String> readBinaryWatch(int num) {
            List<String> res=new ArrayList<>();
            int[] bit=new int[10];
            solve(res,bit,num,0);
            return res;
        }
        void solve( List<String> res,int[] bit,int num,int idx){
            if(num==0){
                int hour=bit[0]+(bit[1]<<1)+(bit[2]<<2)+(bit[3]<<3);
                int minute=bit[4]+(bit[5]<<1)+(bit[6]<<2)+(bit[7]<<3)+(bit[8]<<4)+(bit[9]<<5);
                if(hour<12 && minute<60){
                    res.add(""+hour+(minute<10?":0":":")+minute);
                }
                return;
            }
            for(int i=idx;i<10;i++){
                bit[i]=1;
                solve(res,bit,num-1,i+1);
                bit[i]=0;
            }
        }
    }
    

Log in to reply
 

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