Can someone help explain why this solution is slow and how to correct it?


  • 0
    B
    public class BinaryWatch {
    
      public List<String> readBinaryWatch(int num) {
        Set<String> result = new HashSet<>(100);
        readBinaryWatch(result, num, 0, 0);
        return new ArrayList(result);
      }
    
      private void readBinaryWatch(Set<String> result, int num, int hours, int minutes) {
        if (num == 0) {
          if (hours >= 0 && hours < 12 && minutes >= 0 && minutes <= 59) {
            result.add(String.format("%d:%02d", hours, minutes));
          }
          return;
        }
    
        for (int i = 0; i < 4; ++i) {
          if ((hours & (1 << i)) == 0) {
            hours |=  (1 << i);
            readBinaryWatch(result, num - 1, hours, minutes);
            hours &= ~(1 << i);
          }
        }
    
        for (int i = 0; i < 6; ++i) {
          if ((minutes & (1 << i)) == 0) {
            minutes |= (1 << i);
            readBinaryWatch(result, num - 1, hours, minutes);
            minutes &= ~(1 << i);
          }
        }
      }
    
    

Log in to reply
 

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