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

题目

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);
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章