Leetcode - Binary Watch

My code:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    int[] minute = new int[]{1, 2, 4, 8, 16, 32};
    int[] hour = new int[]{1, 2, 4, 8};
    public List<String> readBinaryWatch(int num) {
        List<String> ret = new ArrayList<String>();
        if (num < 0) {
            return ret;
        }
        
        for (int i = 0; i <= 3 && i <= num; i++) {
            List<String> hours = helper(i, hour, true);
            List<String> minutes = helper(num - i, minute, false);
            for (String h : hours) {
                for (String m : minutes) {
                    ret.add(h + ":" + m);
                }
            }
        }
        
        return ret;
    }
    
    private List<String> helper(int n, int[] nums, boolean isHour) {
        List<String> ret = new ArrayList<String>();
        if (n <= 0) {
            if (isHour) {
                ret.add("0");
            }
            else {
                ret.add("00");
            }
            return ret;
        }
        if (isHour) {
            dfs(0, n, nums, 0, ret, 12);
        }
        else {
            dfs(0, n, nums, 0, ret, 60);
        }
        return ret;
    }
    
    private void dfs(int begin, int n, int[] nums, int sum, List<String> ret, int max) {
        if (begin >= nums.length) {
            if (n == 0 && sum < max) {
                String temp = String.valueOf(sum);
                if (temp.length() == 1 && max == 60) {
                    temp = "0" + temp;
                }
                ret.add(temp);
            }
            return;
        }
        else {
            int curr = nums[begin];
            dfs(begin + 1, n - 1, nums, sum + curr, ret, max);
            dfs(begin + 1, n, nums, sum, ret, max);
        }
    }
}

并不是一道难题,但是觉得应该是 medium,因为也不是瞬秒的。
整体过程写起来,至少得10分钟吧。
然后还有一些Corner case, 比如 1分钟的时候得显示 01
等等。
然后主体思路就是 backtracking
还是遵循原则,每一层只管验证每一层自己。然后在最后一层的下一层,终止。

Anyway, Good luck, Richardo! — 09/19/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/abf5145a922c#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞