Leetcode: 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). Each LED represents a zero or one, with the least significant bit on the right. For example, the above binary watch reads "3:25". 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: 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: 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".
![](https://upload.wikimedia.org/wikipedia/commons/8/8b/Binary_clock_samui_moon.jpg)
Solution 1: Bit Manipulation
use Integer.bitCount()
1 public class Solution { 2 public List<String> readBinaryWatch(int num) { 3 List<String> res = new ArrayList<String>(); 4 for (int i=0; i<12; i++) { 5 for (int j=0; j<60; j++) { 6 if (Integer.bitCount(i) + Integer.bitCount(j) == num) { 7 String str1 = Integer.toString(i); 8 String str2 = Integer.toString(j); 9 res.add(str1 + ":" + (j<10? "0"+str2 : str2)); 10 } 11 } 12 } 13 return res; 14 } 15 }
Solution 2: Backtracking, 非常精妙之处在于用了两个数组来帮助generate digit(例如:1011 -> 11)
1 public class Solution { 2 public List<String> readBinaryWatch(int num) { 3 int[] nums1 = new int[]{8, 4, 2, 1}, nums2 = new int[]{32, 16, 8, 4, 2, 1}; 4 List<String> res = new ArrayList<String>(); 5 for (int i=0; i<=num; i++) { 6 List<Integer> hours = getTime(nums1, i, 12); 7 List<Integer> minutes = getTime(nums2, num-i, 60); 8 for (int hour : hours) { 9 for (int minute : minutes) { 10 res.add(hour + ":" + (minute<10? "0"+minute : minute)); 11 } 12 } 13 } 14 return res; 15 } 16 17 public List<Integer> getTime(int[] nums, int count, int limit) { 18 List<Integer> res = new ArrayList<Integer>(); 19 getTimeHelper(res, count, 0, 0, nums, limit); 20 return res; 21 } 22 23 public void getTimeHelper(List<Integer> res, int count, int pos, int sum, int[] nums, int limit) { 24 if (count == 0) { 25 if (sum < limit) 26 res.add(sum); 27 return; 28 } 29 for (int i=pos; i<nums.length; i++) { 30 getTimeHelper(res, count-1, i+1, sum+nums[i], nums, limit); 31 } 32 } 33 }