A Backtracking solution using Java


  • 0
    F
    public class Solution {
        
        public List<String> readBinaryWatch(int num) {
            List<String> res = new ArrayList<>();
            
            if(num>=0 && num<=8) {
                readWatch(num, 0, 0, 0, res);
            }
            
            return res;
        }
        
        private void readWatch(int num, int cur, int min, int hr, List<String> res) {
            if(num == 0) {
                res.add(read(min, hr));
            } else {
                for(int idx = cur; idx < 10; idx++) {
                    if(idx < 6) {
                        if(min+(1 << idx) <= 59) {
                            readWatch(num-1, idx+1, min+(1 << idx), hr, res);
                        }
                    } else {
                        if(hr+(1 << idx-6) <= 11) {
                            readWatch(num-1, idx+1, min, hr+(1 << idx-6), res);
                        }
                    }
                }
            }
        }
        
        private String read(int min, int hr) {
            StringBuilder sb = new StringBuilder();
            
            sb.append(Integer.toString(hr)).append(":");
            if(min <= 9) {
                sb.append("0");
            }
            sb.append(Integer.toString(min));
            
            return sb.toString();
        }
    }
    

Log in to reply
 

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