leetcode401二进制手表

401

二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。
每个 LED 代表一个 0 或 1,最低位在右侧。

思路 回溯,每一位可选可不选,总选数是num,

nums[11]=[0,0,0,0,0,0,0,0,0,0,0];//多一位表示从1开始到10 
num=2的执行结果
1 1 0 0 0 0 0 0 0 0 
1 0 1 0 0 0 0 0 0 0 
1 0 0 1 0 0 0 0 0 0 
1 0 0 0 1 0 0 0 0 0 
1 0 0 0 0 1 0 0 0 0 
1 0 0 0 0 0 1 0 0 0 
1 0 0 0 0 0 0 1 0 0 
1 0 0 0 0 0 0 0 1 0 
1 0 0 0 0 0 0 0 0 1 
0 1 1 0 0 0 0 0 0 0 
0 1 0 1 0 0 0 0 0 0 
0 1 0 0 1 0 0 0 0 0 
0 1 0 0 0 1 0 0 0 0 
0 1 0 0 0 0 1 0 0 0 
0 1 0 0 0 0 0 1 0 0 
0 1 0 0 0 0 0 0 1 0 
0 1 0 0 0 0 0 0 0 1 
0 0 1 1 0 0 0 0 0 0 
0 0 1 0 1 0 0 0 0 0 
0 0 1 0 0 1 0 0 0 0 
0 0 1 0 0 0 1 0 0 0 
0 0 1 0 0 0 0 1 0 0 
0 0 1 0 0 0 0 0 1 0 
0 0 1 0 0 0 0 0 0 1 
0 0 0 1 1 0 0 0 0 0 
0 0 0 1 0 1 0 0 0 0 
0 0 0 1 0 0 1 0 0 0 
0 0 0 1 0 0 0 1 0 0 
0 0 0 1 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 0 1 
0 0 0 0 1 1 0 0 0 0 
0 0 0 0 1 0 1 0 0 0 
0 0 0 0 1 0 0 1 0 0 
0 0 0 0 1 0 0 0 1 0 
0 0 0 0 1 0 0 0 0 1 
0 0 0 0 0 1 1 0 0 0 
0 0 0 0 0 1 0 1 0 0 
0 0 0 0 0 1 0 0 1 0 
0 0 0 0 0 1 0 0 0 1 
0 0 0 0 0 0 1 1 0 0 
0 0 0 0 0 0 1 0 1 0 
0 0 0 0 0 0 1 0 0 1 
0 0 0 0 0 0 0 1 1 0 
0 0 0 0 0 0 0 1 0 1 
0 0 0 0 0 0 0 0 1 1 
class Solution {
public:
    void rbw(vector<int> &nums,vector<vector<int>> &res,int num,int begin,int end)
    {
        if(num==0&&begin==end)
        {
            res.push_back(nums);
            return;
        }
        else if(begin<end)
        {
            nums[begin]=1;//begin=10时,end=10,无法入队列
            rbw(nums,res,num-1,begin+1,end);
            nums[begin]=0;
            rbw(nums,res,num,begin+1,end);
        }
    }
    void change(vector<string> &ress,vector<vector<int>> res)
    {
        int len=res.size();
        int i,j,k;
        int hour=0,minute=0;

        for(i=0;i<len;i++)
        {
            for(k=1;k<=10;k++)
                cout<<res[i][k]<<" ";
            cout<<endl;
            hour=0;minute=0;
            for(j=1;j<=4;j++)
            {
                hour=hour*2+res[i][j];
            }
            for(;j<=10;j++)
            {
                minute=minute*2+res[i][j];
            }
            if(hour<12&&minute<60)
            {
                string r="";
                r=r+to_string(hour)+":";
                if(minute>=10)
                    r=r+to_string(minute);
                else
                    r=r+"0"+to_string(minute);
                ress.push_back(r);
            }

        }
        
    }
    vector<string> readBinaryWatch(int num) {
        vector<int> nums;
        int i;
        for(i=0;i<=11;i++)
            nums.push_back(0);
        vector<vector<int>> res;
        rbw(nums,res,num,1,11);
        //这个地方注意。多一是为了让最后一位改变或者不改变后能入结果队列
        vector<string> ress;
        change(ress,res);
        return ress;
    }
};
原创文章 23 获赞 26 访问量 436

猜你喜欢

转载自blog.csdn.net/weixin_41672404/article/details/105910689
今日推荐