[leetcode]: 401. Binary Watch
来源:互联网 发布:matlab 随机字符串数组 编辑:程序博客网 时间:2024/06/14 21:22
1.题目
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.
Example:
Input: n = 1
Return: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, “0:08”, “0:16”, “0:32”]
2.分析
有两种方法
方法一:
先确定小时和分钟各有多少个1,再求和计算小时和分钟。
做排列组合求和,小时有x个1,分钟有n-x个1。然后每个1出现在哪一位做排列组合。
方法二:
反向思考。
先确定小时和分钟的数字,再判断是否满足bit为1的位数为n。
小时0-11,分钟0-59.两个for循环嵌套遍历,计算当前循环的数字bit为1的数目,如果总数刚好是n则为一个符合要求的时间。
3.代码
方法1,排列组合
vector<string> readBinaryWatch(int num,int m) { vector<int> hour = { 1,2,4,8 }; vector<int> minute = { 1,2,4,8,16,32 }; vector<string> ans; for (int i = 0; i <= num; i++) { unordered_set<int> hours = generateTime(hour, i); unordered_set<int> minutes = generateTime(minute, num - i); for (int h : hours) { if (h < 12) { for (int m : minutes) { if (m < 60) ans.push_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m)); } } } }}unordered_set<int> generateTime(vector<int> base, int count) { unordered_set<int> times; permutate(base, count, 0, 0, times); return times;}void permutate(vector<int> base, int count, int pos, int sum, unordered_set<int>& times) { if (count == 0) { times.insert(sum); return; } for (int i = pos; i < base.size(); i++) permutate(base, count - 1, i + 1, sum + base[i], times);}
方法2,数bit为1的位数
int bitcount(int n) { int count = 0; while (n) { n = n&(n - 1); ++count; } return count;}vector<string> readBinaryWatch(int num) { vector<string> ans; for (int i = 0; i < 12; i++) { for (int j = 0; j < 60; j++) { if (bitcount(i*64 + j) == num) ans.push_back(to_string(i) + (j < 10 ? ":0" : ":") + to_string(j)); } } return ans;}
阅读全文
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
- 401. [LeetCode]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
- sql语句case when使用和date_formate()的使用,DATEDIFF(字段1,字段2)获取天数,常用的MYSQL的函数
- javaweb自动登录(cookie)
- 170522 逆向-控制语句的汇编和优化
- rapidjson 使用总结
- Instant Apps是什么和实现原理
- [leetcode]: 401. Binary Watch
- Gym
- 第二行代码第三章笔记
- Redis in Python: Redis的安装
- 2017-5-21.22 C++primer笔记~
- webpack---webpack.config.js配置基本要素entry、output、loader、plugins等
- oracle linux 6.9通过UDEV创建裸设备
- MANIFEST.MF文件全面解析
- 《大话数据结构》读书笔记(1)