java dfs solution with BitSet


  • 0
    B
        private void addTime(List<String> list, BitSet bs) {
            int hour, minute, i;
            
            for (hour = i = 0; i < 4; i++)
                if (bs.get(i))
                    hour += (1 << i);
            
            for (minute = 0; i < 10; i++)
                if (bs.get(i))
                    minute += (1 << (i - 4));
            
            if (hour <= 11 && minute <= 59)
                list.add(String.format("%d:%02d", hour, minute));
        }
        
        private void readBinaryWatchInt(int num, List<String> list, BitSet bs, int ind) {
            if (num == 0) {
                addTime(list, bs);
                return;
            }
            for (int i = ind; i < 10; i++)
                if (!bs.get(i)) {
                    bs.set(i);
                    readBinaryWatchInt(num - 1, list, bs, i + 1);
                    bs.clear(i);
                }
        }
        
        public List<String> readBinaryWatch(int num) {
            List<String> list = new ArrayList<>();
            readBinaryWatchInt(num, list, new BitSet(10), 0);
            return list;
        }
    

Log in to reply
 

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