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