Easy to understand O(1) space (not including recursive stack) solution Java


  • 0
    T
    public class Solution {
        public List<String> readBinaryWatch(int num) {
            List<String> list = new ArrayList<>();
            helper(0, 0, 0, 0, num, list);
            return list;
        }
        
        private void helper(int hrIndex, int minIndex, int hrs, int mins, int num, List<String> list){
            if( hrs > 11 || mins > 59) return;
            if(num == 0){
                    String time = buildTime(hrs, mins);
                    if(!list.contains(time)){
                        list.add(time);
                    }
                return;
            }
            if(hrIndex == 5 || minIndex == 7) return;
            
            for(int i = minIndex; i<6; i++){
                helper(hrIndex, i+1, hrs, mins+(1<<(i)),num-1, list);
            }
            
            for(int i = hrIndex; i<4;i++){
                helper(i+1, minIndex, hrs+(1<<(i)), mins,num-1, list);
            }
        }
        
        private String buildTime(int hrs, int mins){
            StringBuilder sb = new StringBuilder();
            sb.append(hrs+":");
            if(mins<10){
                sb.append("0");
            }
            sb.append(mins);
            return sb.toString();
        }
    }

Log in to reply
 

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