2ms Java solution with back track


  • 0
    Q
    public class Solution {
        public List<String> readBinaryWatch(int num) {
            int[] time = new int[] {8,4,2,1,32,16,8,4,2,1};
            int[] comb = new int[2];
            List<int[]> posComb = new ArrayList<>();
            Combines(num,0,0,0,time,posComb);
            
            List<String> res = new ArrayList<>();
            for (int[] temp: posComb) {
                String s = "";
                if (temp[0]<12 && temp[1]<60) {
                    if (temp[1]<10) {
                        s = temp[0] + ":0" + temp[1];
                    }
                    else {
                        s = temp[0] + ":" + temp[1];
                    }
                    res.add(s);
                }
            }
            return res;
        }
        
        public void Combines (int count, int pos, int hour,int minute, int[] time, List<int[]> posComb) {
            if (count==0) {
                posComb.add(new int[]{hour,minute});
                return;
            }
            if (pos>9 || count>10-pos) return;
            
            Combines(count,pos+1,hour,minute,time,posComb);
            if (pos<4) {
                Combines(count-1,pos+1,hour+time[pos],minute,time,posComb);
            }
            else Combines(count-1,pos+1,hour,minute+time[pos],time,posComb);
        }
    }
    

Log in to reply
 

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