Simple Space Search Solution


  • 0
    public class Solution {
        public List<String> readBinaryWatch(int num) {
            return dfs(0, 0, num, 0, new ArrayList<>());
        }
        
        List<String> dfs(int index, int count, int total, int captured, List<String> results) {
            if (index > 10) return results;
            if (count == total) {
                if (valid(captured)) results.add(toString(captured));
            } else {
                dfs(index + 1, count + 1, total, captured | (1 << index), results);
                dfs(index + 1, count, total, captured, results);
            }
            
            return results;
        }
        
        boolean valid(int captured) {
            Integer hours = captured & 0x0F;
            Integer minutes = (captured >>> 4);
            
            return hours < 12 && minutes < 60; 
        }
        
        String toString(int captured) {
            Integer hours = captured & 0x0F;
            Integer minutes = (captured >>> 4);
            
            return String.format("%s:%s", hours, ("00" + minutes).substring(minutes.toString().length()));
        }
    }
    

Log in to reply
 

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