LeetCode:实现二进制表的所有组合

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 siganification 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 would could represent.

Example 1:
Input:1
Output: ["1:00","2:00","4:00","8:00","0:01","0:02","0:04","0:08","0:16","0:32"]

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".

解题思路:
参考LeetCode的一位大神,使用两层遍历,然后利用二进制转换结果与目标值进行对比.此外可以直接通过,
bitset<10>((i<<6)|j).count()==num,就可以省略digittonum函数.
方法2
回溯法
*/
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Solution{
public:
    vector<string> readBinaryWatch(const int& num){
        vector<string> res;
        for(auto i=0;i<12;i++){
            for(auto j=0;j<60;j++){
                if(digittonum(i)+digittonum(j)==num){
                    res.push_back(to_string(i)+":"+(j<10?"0"+to_string(j):to_string(j)));
                }
            }
        }
        return res;
    }
private:
    int digittonum(int a){
        int num=0;
        while(a){
            a=a&(a-1);
            num++;
        }
        return num;
    }
};

int main(int argc,char* argv[]){
    const int num=2;
    vector<string> res=Solution().readBinaryWatch(num);
    for(auto& i:res)
       cout<<i<<endl;
    return 0;
}

Go语言实现

package main

import (
	"fmt"
	"strconv"
)

func readBinaryWatch(n int)(res []string){
	time:=[][]int{{0,0}}
	nums:=[]int{1,2,4,8,1,2,4,8,16,32}
	watchofbfs(nums,&time,0,n,&res)
	return
}

func watchofbfs(nums []int,time *[][]int,index,num int,res *[]string){
	if num==0{
		if (*time)[0][0]>11||(*time)[0][1]>59{
			return
		}
		hour:=strconv.Itoa((*time)[0][0])
		minute:=strconv.Itoa((*time)[0][1])
		if len(minute)==1{
			minute="0"+minute
		}
		*res=append(*res,hour+":"+minute)
		return
	}
	for i:=index;i<10;i++{
		temp:=[]int{0,0}
		temp[0]=(*time)[0][0]
		temp[1]=(*time)[0][1]
		if i<4{
			(*time)[0][0]+=nums[i]
		}else{
			(*time)[0][1]+=nums[i]
		}
		watchofbfs(nums,time,i+1,num-1,res)
		(*time)[0][0]=temp[0]
		(*time)[0][1]=temp[1]
	}
}

func main(){
	fmt.Println("求二进制表所有的可能组合")
	fmt.Println(readBinaryWatch(1))
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值