【leetcode】401. 二进制手表

void recursion(int* t, int minute, int hour, int n, int cur, int start, char** arr, int* pst){
    if (minute >= 60 || hour >= 12) return;
    if (cur == n){
        char* s = (char*)calloc(10, sizeof(char));
        int len = sprintf(s, "%d:", hour);
        if (minute <10)
            sprintf(s + len, "0%d", minute);
        else{
            sprintf(s + len, "%d", minute);
        }
        arr[(*pst)++] = s;
        return;
    }
    for (int i = start; i <= cur + 10 - n; i++){
        if (i<6)
            recursion(t, minute + t[i], hour, n, cur + 1, i + 1, arr, pst);
        else
            recursion(t, minute, hour + t[i], n, cur + 1, i + 1, arr, pst);
    }
}
char ** readBinaryWatch(int num, int* returnSize){
    int t[] = { 1, 2, 4, 8, 16, 32, 1, 2, 4, 8 };
    char** arr = (char**)calloc(1000, sizeof(char*));
    int pst = 0;
    recursion(t, 0, 0, num, 0, 0, arr, &pst);
    *returnSize = pst;
    return arr;
}
//C++
class Solution {
public:
    vector<string> readBinaryWatch(int num) {
        vector<string> res;
        //直接遍历  0:00 -> 12:00   每个时间有多少1
        for (int i = 0; i < 12; i++) {
            for (int j = 0; j < 60; j++) {
                if (count1(i) + count1(j) == num) {
                    res.push_back(to_string(i)+":"+
                                  (j < 10 ? "0"+to_string(j) : to_string(j)));
                }
            }
        }
        return res;
    }
    //计算二进制中1的个数
    int count1(int n) {
        int res = 0;
        while (n != 0) {
            n = n & (n - 1);
            res++;
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/ganxiang/p/14058703.html