Straightforward JAVA solution


  • 0
    C
    public class Solution
    {
        ArrayList<String> list = new ArrayList<String>();
        
        public List<String> readBinaryWatch(int num)
        {
            int[] look = new int[]{8, 4, 2, 1, 32, 16, 8, 4, 2, 1};
            
            if(num == 0)
            {
                list.add("0:00");
                return list;
            }
            
            boolean[] state = new boolean[10];
            
            permute(state, look, 0, num, 0);
            
            return list;
        }
        
        private void permute(boolean[] state, int[] look, int depth, int num, int start)
        {
            if(num == depth)
            {
                int hours = 0;
                
                int j = 0;
                
                for(; j < 4; j++)
                {
                    if(state[j])
                    {
                        hours += look[j];
                    }
                }
                
                if(hours <= 11)
                {
                    int mins = 0;
                    
                    for(; j < 10; j++)
                    {
                        if(state[j])
                        {
                            mins += look[j];
                        }
                    }
                    
                    if(mins <= 59)
                    {
                        String time = hours + ":";
                        if(mins <= 9)
                        {
                            time += "0";
                        }
                        time += mins;
                        
                        list.add(time);
                    }
                }
                
                return;
            }
            
            for(int i = start; i < 10; i++)
            {
                state[i] = true;
                permute(state, look, depth + 1, num, i + 1);
                state[i] = false;
            }
        }
        
        
    }

Log in to reply
 

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