leetcode[Binary Watch]
来源:互联网 发布:淘宝魔镜软件管用吗 编辑:程序博客网 时间:2024/06/05 15:07
解法一:
public class Solution { private List<Integer> generateDigit(int[] nums, int count) {//利用回溯法求解时针和分针的排列组合 List<Integer> res = new ArrayList<>(); generateDigitHelper(nums, count, 0, 0, res); return res; } //用递归来实现回溯 private void generateDigitHelper(int[] nums, int count, int pos, int sum, List<Integer> res) { if(count == 0) {//递归出口 res.add(sum); return; } for(int i = pos; i < nums.length; i++) {//这其实就是在进行DFS遍历,先走完i,再走i+1,i+2... generateDigitHelper(nums, count - 1, i + 1, sum + nums[i], res); } } 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);//得到时针在有i个灯亮时可能的组合数 List<Integer> list2 = generateDigit(nums2, num - i);//得到分针在有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));//用一个三元运算符就解决格式问题 //等价于: res.add(String.format("%d:%02d", num1,num2)); 通过%02d来调整格式 } } } return res; }}
解法二:
public class Solution {//Just go through the possible times and collect those with the correct number of one-bits.public List<String> readBinaryWatch(int num) { List<String> times = new ArrayList<>(); for (int h=0; h<12; h++) for (int m=0; m<60; m++) if (Integer.bitCount(h) + Integer.bitCount(m) == num)//bitCount函数的妙用 times.add(String.format("%d:%02d", h, m));//用格式输出也能调整格式 return times; }}
阅读全文
0 0
- 【Leetcode】401. Binary Watch
- LeetCode 401 Binary Watch
- leetcode 401 Binary Watch
- [LeetCode]401. Binary Watch
- LeetCode 401. Binary Watch
- [leetcode]401. Binary Watch
- leetcode 401: Binary Watch
- Leetcode 401 Binary Watch
- Leetcode 401. Binary Watch
- LeetCode 401. Binary Watch
- LeetCode 401. Binary Watch
- LeetCode 401. Binary Watch
- leetcode 401. Binary Watch
- Leetcode Binary Watch 401
- 【LeetCode】 401. Binary Watch
- [leetcode][401]. Binary Watch
- [LeetCode]401. Binary Watch
- 401. [LeetCode]Binary Watch
- JQ实现效果:焦点选中样式
- Oracle 10g RAC修改public ip、vip和private ip
- mysql数据库最大连接数设置
- Unity 3D之调用摄像头并存储
- Sailing(BFS 金马五校赛-东华大学 )
- leetcode[Binary Watch]
- Android在子线程更新UI界面
- springboot 使用自己的fastJson框架
- 动态规划7:最长上升子序列LIS
- 乱七八糟
- Android
- python连接mysql和sqlsever驱动
- 关于不同像素设备替换不同图片的问题
- 最短路问题,多源、SPFA变形