Leetcode: Binary Watch

时间:2023-03-28 12:33:38
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".
Leetcode: Binary Watch

Solution 1: Bit Manipulation

use   Integer.bitCount()

 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;
}
}

Solution 2: Backtracking, 非常精妙之处在于用了两个数组来帮助generate digit(例如:1011 -> 11)

 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);
}
}
}