-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathbinaryWatch.java
More file actions
38 lines (38 loc) · 1.62 KB
/
Copy pathbinaryWatch.java
File metadata and controls
38 lines (38 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Solution {
public List<String> readBinaryWatch(int num) {
List<String> res = new ArrayList<>();
/* use a hashtable to represent digit lights for hours and minutes */
int[] nums1 = {8, 4, 2, 1}, nums2 = {32, 16, 8, 4, 2, 1};
for(int i = 0; i <= num; i++){
/* assign lights to hours and get hour comboniation time */
List<Integer> list1 = generateDigit(nums1, i);
/* assign rest to minutes and get all miniute combonation time */
List<Integer> list2 = generateDigit(nums2, num - i);
/* get the valid combonation of these two lists */
for(int num1 : list1){
if(num1 > 11) continue;/* hour represet 0-11 */
for(int num2 : list2){
if(num2 >= 60) continue;/* minute represts with 0-59 */
res.add(num1 + ":" + (num2 < 10 ? "0" + num2 : num2));
}
}
}
return res;
}
//generate all possible digit for the specified light number
public List<Integer> generateDigit(int[] num, int count){
List<Integer> res = new ArrayList<>();
generateDigitHelper(num, count, 0, 0, res);
return res;
}
//a helper method to combonation the digits
private void generateDigitHelper(int[] num, int count, int position, int calculated, List<Integer> res){
if(count == 0){
res.add(calculated);
} else {
for(int i = position; i < num.length; i++){
generateDigitHelper(num, count - 1, i + 1, calculated + num[i], res);
}
}
}
}