【LeetCode】401. Binary Watch
来源:互联网 发布:edg网络黄金官方网站 编辑:程序博客网 时间:2024/06/04 00:43
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.
For example, the above binary watch reads “3:25”.
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
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"]
Note:
- The order of output does not matter.
- The hour must not contain a leading zero, for example “01:00” is not valid, it should be “1:00”.
- The minute must be consist of two digits and may contain a leading zero, for example “10:2” is not valid, it should be “10:02”.
想吐槽一下 这个EASY题目AC的还真的不容易,花了我不少时间 - -。
主要思路是用一个0,1数组来模拟这十个LED灯,然后对这个数组进行全排列,
看有多少种符合条件的情况。
class Solution {public: vector<string> ans; int calTime(int *a,int l,int r){ int sum=0; for(int i=l;i<=r;i++){ sum=sum*2+a[i]; } return sum; } bool isNeedSwap(int *a,int l,int r){ //查找在[l,r)区间中,有没有和a[r]相同的数字 for(int i=l;i<r;i++){ if(a[i]==a[r]){ return false; } } return true; } string timeToString(int hour,int min){ string s; stringstream ss,s1; ss<<hour; s+=ss.str(); s+=':'; s1<<min; if(min<10) s+='0'; string r=s1.str(); s+=r; return s; } void permutation(int *a,int l,int r){ //全排列 if(l==r){ int hour=calTime(a,0,3); int minute=calTime(a,4,9); if(hour<12&&minute<60){ ans.push_back(timeToString(hour,minute)); } }else{ for(int i=l;i<=r;i++){ if(!isNeedSwap(a,l,i))continue; //考虑有重复数字的情况 swap(a[i],a[l]); permutation(a,l+1,r); swap(a[i],a[l]); } } } vector<string> readBinaryWatch(int num) { int a[10]; for(int i=0;i<10;i++){ if(i<10-num){ a[i]=0; }else{ a[i]=1; } } permutation(a,0,9); 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
- Java静态属性和方法的继承问题
- java随手笔记
- 深度学习网络调参技巧
- Linux 文件基本属性
- C语言(Head First C)-6_1:结构、联合与位字段:创建自己的结构
- 【LeetCode】401. Binary Watch
- js cavas截图
- 史上最简单的SpringCloud教程 | 第六篇: 分布式配置中心(Spring Cloud Config)
- Redis与Memcached的区别
- 4.18 leetcode -18 single-number
- get_lantern::std::operator
- 关于Google Chrome启动时启动页面被毒霸篡改的解决办法
- Eclipse快捷键大全
- Spring学习——Spring中定时器实现