LeetCode - 401. Binary Watch - 思路详解-C++

48 篇文章 0 订阅
43 篇文章 0 订阅

题目

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.

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

翻译

一个二进制手表,4个LED在顶部,表示小时从0~11。6个LED在底部,表示分钟 0 ~ 59
每个LED表示为0或者1,右边最低有效位。

给一个正整数,表示整个手表点亮的LED的个数。返回所有可能的时间。

思路详解

该题目是一道排列组合的题目。
假设,总的LED点亮了3个。则有四种可能
1,小时LED亮0个,分钟LED亮3个
2,小时LED-> 1个,分钟LED->2个
3,小时LED->2个,分钟LED->1个
4,小时LED->3个,分钟LED->0个

通过例子,可以得到一个简明的思路
1,分钟和小时所有点亮的个数的可能遍历。
2,分钟点亮的个数,所有可能代表的分钟值和小时点亮的个数所代表的的值,然后全组合,即可。

代码

class Solution {
public:

    vector<string> readBinaryWatch(int num) {
        vector<string> res;
        vector<int> hour = {1,2,4,8};
        vector<int> minute = {1,2,4,8,16,32};
        for(int i = 0; i <= num; i ++){
            vector<int> v_hour = getAllPossible(hour,i);  //当小时只有i个亮的时候,所有可能性
            vector<int> v_min = getAllPossible(minute,num-i);   //所有可能的分钟
            for(int num1:v_hour){
                if(num1 >= 12) continue;
                for(int num2:v_min){
                    if(num2 > 60) continue;
                    res.push_back(to_string(num1) + ":" + (num2 < 10 ? "0" + to_string(num2):to_string(num2)));
                }
            }
        }
        return res;
    }

    vector<int> getAllPossible(vector<int> nums,int count){
        vector<int> res;
        getAllPossible(nums,count,0,0,res);
        return res;
    }

    void getAllPossible(vector<int> nums,int count,int pos,int sum,vector<int> &res){
        if(count == 0){
            res.push_back(sum);
            return;
        }

        for(int i = pos; i < nums.size();i ++){
            //向后遍历
            getAllPossible(nums,count-1,i+1,sum+nums[i],res);
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值