EASY题

401. Binary Watch

2017-07-22  本文已影响17人  DrunkPian0

这题我的思路是用一个长度是10的数组,随机地把1洒落在这个这个数组上,然后对前4个做计算,后6个做计算,拼接起来就行了。问题出怎么才能遍历到所有的撒落的可能性。首先我事先不知道n是几,所以不能提前写好n个for。所以,我感觉这题应该用递归。

看答案了。
先用一个别人的有点trick的方法(但是这个方法并不能解释我上面的疑惑,就是怎么找出所有散落的可能性):bitCount。计算0:00到11:59里面所有可能的值然后对比bitCount跟num对比,对得上就输出。挺巧妙的,不过这种需要遍历所有的时间,真的好吗。


    public List<String> readBinaryWatch(int num) {
        List<String> res = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            for (int j = 0; j < 60; j++) {
                if (Integer.bitCount(i) + Integer.bitCount(j) == num) {
                    res.add(String.format("%d:%02d", i, j));
                }
            }
        }
        return res;
    }

dfs

这题确实是可以用permutation+combination做的。
https://discuss.leetcode.com/topic/59494/3ms-java-solution-using-backtracking-and-idea-of-permutation-and-combination

上一篇 下一篇

猜你喜欢

热点阅读