Thinking process

Step by step

  • do two backtracking

Mistakes

Don't forget to skip the cases that hours >= 12 or minutes >= 60

public class Solution {
    public List<String> readBinaryWatch(int num) {
        List<String> result = new ArrayList<>();
        int[] hours = {8, 4, 2, 1};
        int[] minutes = {32, 16, 8, 4, 2, 1};
        for (int i = 0; i <= num; i++) {
            List<Integer> hoursList = new ArrayList<>();
            readBinaryWatchDfsHelper(hoursList, hours, 0, i, 0);

            List<Integer> minutesList = new ArrayList<>();
            readBinaryWatchDfsHelper(minutesList, minutes, 0, num - i, 0);

            for (int h : hoursList) {
                if (h >= 12) continue;
                for (int m : minutesList) {
                    if (m >= 60) continue;
                    result.add(h + ":" + (m < 10 ? "0" : "") + m);
                }
            }
        }

        return result;
    }

    //return all possible combination sums of n numbers of integers in nums
    private void readBinaryWatchDfsHelper(List<Integer> result, int[] nums, int sum, int n, int index) {
        if (n == 0) {
            result.add(sum);
            return;
        }

        for (int i = index; i < nums.length; ++i) {
            readBinaryWatchDfsHelper(result, nums, sum + nums[i], n - 1, i + 1);
        }
    }
}

results matching ""

    No results matching ""