Problem
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:
|
|
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”.
Solution 1
The following code goes through all possible times, and checks if the time has correct number of one-bit.
|
|
Note:Integer.bitCount(N)
returns the number of one-bits in the two’s complement binary representation of the specified int value N.
Solution 2
The following code describes the framework of the solution:
|
|
Thus, the first thing we need to solve is how to select r elements from an array with n elements?
My idea is to permutate the array, and select the first r elements.
Example
|
|
The following code calculates all permutations of an array, select the first r elements of each permutation, and removes duplicates with the help of HashSet
.
|
|
The above code is an important framework of permutation problems. It could be explained as:
|
|
After solving selecting r elements from an array with n elements, we can move on to construct the time with the hour and minute we get.
The complete code is as follows:
|
|
Written with StackEdit.