-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinaryWatch.java
61 lines (54 loc) · 1.53 KB
/
BinaryWatch.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : BinaryWatch
* Creator : Edward
* Date : Nov, 2017
* Description : 401. Binary Watch
*/
public class BinaryWatch {
/**
* num = 5
* [8, 4, 2, 1] count = 2
*
* time : 不知道
* space : O(n)
*
* @param num
* @return
*/
public List<String> readBinaryWatch(int num) {
List<String> res = new ArrayList<>();
int[] nums1 = new int[]{8, 4, 2, 1};
int[] nums2 = new int[]{32, 16, 8, 4, 2, 1};
for (int i = 0; i <= num; i++) {
List<Integer> list1 = generateDigit(nums1, i);
List<Integer> list2 = generateDigit(nums2, num - i);
for (int num1 : list1) {
if (num1 >= 12) continue;
for (int num2 : list2) {
if (num2 >= 60) continue;
res.add(num1 + ":" + (num2 < 10 ? "0" + num2 : num2));
}
}
}
return res;
}
private List<Integer> generateDigit(int[] nums, int count) {
List<Integer> res = new ArrayList<>();
helper(res, nums, count, 0, 0);
return res;
}
private void helper(List<Integer> res, int[] nums, int count, int start, int sum) {
if (count == 0) {
res.add(sum);
return;
}
for (int i = start; i < nums.length; i++) {
helper(res, nums, count - 1, i + 1, sum + nums[i]);
}
}
}