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).html
Each LED represents a zero or one, with the least significant bit on the right.git
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 could represent.函數
Example:spa
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
Note:3d
首先來看一種寫法很簡潔的解法,這種解法利用到了bitset這個類,能夠將任意進制數轉爲二進制,並且又用到了count函數,用來統計1的個數。那麼時針從0遍歷到11,分針從0遍歷到59,而後咱們把時針的數組左移6位加上分針的數值,而後統計1的個數,即爲亮燈的個數,咱們遍歷全部的狀況,當其等於num的時候,存入結果res中,參見代碼以下: code
class Solution { public: vector<string> readBinaryWatch(int num) { vector<string> res; for (int h = 0; h < 12; ++h) { for (int m = 0; m < 60; ++m) { if (bitset<10>((h << 6) + m).count() == num) { res.push_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m)); } } } return res; } };
上面的方法之因此那麼簡潔是由於用了bitset這個類,若是咱們不用這個類,那麼應該怎麼作呢?這個燈亮問題的本質其實就是在n個數字中取出k個,那麼就跟以前的那道Combinations同樣,咱們能夠借鑑那道題的解法,那麼思路是,若是總共要取num個,咱們在小時集合裏取i個,算出和,而後在分鐘集合裏去num-i個求和,若是兩個都符合題意,那麼加入結果中便可,參見代碼以下:htm
解法二:blog
class Solution { public: vector<string> readBinaryWatch(int num) { vector<string> res; vector<int> hour{8, 4, 2, 1}, minute{32, 16, 8, 4, 2, 1}; for (int i = 0; i <= num; ++i) { vector<int> hours = generate(hour, i); vector<int> minutes = generate(minute, num - i); for (int h : hours) { if (h > 11) continue; for (int m : minutes) { if (m > 59) continue; res.push_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m)); } } } return res; } vector<int> generate(vector<int>& nums, int cnt) { vector<int> res; helper(nums, cnt, 0, 0, res); return res; } void helper(vector<int>& nums, int cnt, int pos, int out, vector<int>& res) { if (cnt == 0) { res.push_back(out); return; } for (int i = pos; i < nums.size(); ++i) { helper(nums, cnt - 1, i + 1, out + nums[i], res); } } };