401. Binary Watch

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).html

Each LED represents a zero or one, with the least significant bit on the right.java

For example, the above binary watch reads "3:25".git

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.函數

Example:code

Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

 

Note:htm

  • The order of output does not matter.
  • The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
  • The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".

這種解法利用到了bitset這個類,能夠將任意進制數轉爲二進制,並且又用到了Integer.bitCount()函數,用來統計1的個數。那麼時針從0遍歷到11,分針從0遍歷到59,bitCount 方法是用來統計參數i轉成2進制後有多少個1blog

public class Solution {
    public List<String> readBinaryWatch(int num) {
        List<String> res = new ArrayList<String>();
        for (int i=0; i<12; i++) {
            for (int j=0; j<60; j++) {
                if (Integer.bitCount(i) + Integer.bitCount(j) == num) {
                    String str1 = Integer.toString(i);
                    String str2 = Integer.toString(j);
                    res.add(str1 + ":" + (j<10? "0"+str2 : str2));
                }
            }
        }
        return res;
    }
}

  上面的方法之因此那麼簡潔是由於用了bitset這個類,若是咱們不用這個類,那麼應該怎麼作呢?這個燈亮問題的本質其實就是在n個數字中取出k個,那麼就跟以前的那道Combinations同樣,咱們能夠借鑑那道題的解法,那麼思路是,若是總共要取num個,咱們在小時集合裏取i個,算出和,而後在分鐘集合裏去num-i個求和,若是兩個都符合題意,那麼加入結果中便可,參見代碼以下:get

public class Solution {
    public List<String> readBinaryWatch(int num) {
        int[] nums1 = new int[]{8, 4, 2, 1}, nums2 = new int[]{32, 16, 8, 4, 2, 1};
        List<String> res = new ArrayList<String>();
        for (int i=0; i<=num; i++) {
            List<Integer> hours = getTime(nums1, i, 12);
            List<Integer> minutes = getTime(nums2, num-i, 60);
            for (int hour : hours) {
                for (int minute : minutes) {
                    res.add(hour + ":" + (minute<10? "0"+minute : minute));
                }
            }
        }
        return res;
    }
    
    public List<Integer> getTime(int[] nums, int count, int limit) {
        List<Integer> res = new ArrayList<Integer>();
        getTimeHelper(res, count, 0, 0, nums, limit);
        return res;
    }
    
    public void getTimeHelper(List<Integer> res, int count, int pos, int sum, int[] nums, int limit) {
        if (count == 0) {
            if (sum < limit)    
                res.add(sum);
            return;
        }
        for (int i=pos; i<nums.length; i++) {
            getTimeHelper(res, count-1, i+1, sum+nums[i], nums, limit);
        }
    }
}
相關文章
相關標籤/搜索