leetcode 401. Binary Watch
程序员文章站
2022-05-20 23:12:46
...
题目简述:
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).
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
算法思路:
设 i 个小时的bit亮,n-i个分钟的bit亮,分别算出i个bit的若干种组合和n-i个bit的若干种组合,将这2个组合得到的结果合并就可以得到时刻了,i 从0到n。
提交结果:
Runtime: 2 ms, faster than 79.31% of Java online submissions for Binary Watch.
参考代码:
public static List<String> readBinaryWatch(int num) {
List<String> result = new ArrayList<String>();
int[] hour = {1,2,4,8};
int[] min = {1,2,4,8,16,32};
for(int i=0;i<=num;i++){
List<String> resHour = new ArrayList<String>();
List<String> resMin = new ArrayList<String>();
List<Integer> temp = new ArrayList<Integer>();
//找到小时的组合
findHour(hour, resHour, 0, i, temp);
temp.clear();
//找到分钟的组合
findMin(min, resMin, 0, num - i, temp);
// 时与分组合成时刻
for (int j = 0; j < resHour.size(); j++) {
for (int k = 0; k < resMin.size(); k++) {
result.add(resHour.get(j) + ":" + resMin.get(k));
}
}
}
return result;
}
public static void findHour(int[] hour,List<String> result,int index,int count,List<Integer> temp){
if(count==temp.size()){
int sum=0;
for(Integer key:temp)
sum += key;
//最大11时
if(sum<=11)
result.add(String.valueOf(sum));
return;
}
for(int i=index;i<hour.length;i++){
temp.add(hour[i]);
findHour(hour, result, i+1, count, temp);
//恢复 findHour()之前的样子,尝试找下一个元素
temp.remove(temp.size()-1);
}
}
public static void findMin(int[] min,List<String> result,int index,int count,List<Integer> temp){
if(count==temp.size()){
int sum=0;
for(Integer key:temp)
sum += key;
//最大59分钟
if(sum<=59){
if(sum<=9)
result.add('0'+String.valueOf(sum));
else
result.add(String.valueOf(sum));
}
return;
}
for(int i=index;i<min.length;i++){
temp.add(min[i]);
findMin(min, result, i+1, count, temp);
temp.remove(temp.size()-1);
}
}
推荐阅读
-
leetcode笔记:Invert Binary Tree
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
LeetCode C++ 454. 4Sum II【Hash Table/Sort/Two Pointers/Binary Search】
-
【LeetCode】762. Prime Number of Set Bits in Binary Representation
-
LeetCode - easy-762. Prime Number of Set Bits in Binary Representation
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
LeetCode 235--二叉搜索树的最近公共祖先 ( Lowest Common Ancestor of a Binary Search Tree ) ( C语言版 )
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树