2ms clear DFS


  • 0
    G
    public class Solution {
        public List<String> readBinaryWatch(int num) {
            List<String> ret = new ArrayList<>();
            int[] sect = new int[] {8, 4, 2, 1, 32, 16, 8, 4, 2, 1};
            int[] time = new int[] {0, 0};
            helper(num, sect, time, ret, 0);
            return ret;
        }
        
        public void helper(int num, int[] sect, int[] time, List<String> ret, int index) {
            if (num == 0 || index == sect.length) {
                if (time[0] > 11 || time[1] > 59 || num > 0) {
                    return;
                }
                String tmp = "";
                tmp +=  String.valueOf(time[0]);
                tmp += ":";
                String second = String.valueOf(time[1]);
                tmp += second.length() == 1? "0" + second: second;
                ret.add(tmp);
                return;
            }
            if (index < 4) {
                time[0] += sect[index];
                helper(num - 1, sect, time, ret, index + 1);
                time[0] -= sect[index];
            } else {
                time[1] += sect[index];
                helper(num - 1, sect, time, ret, index + 1);
                time[1] -= sect[index];
            }
            helper(num, sect, time, ret, index + 1);
        }
    }
    

Log in to reply
 

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