【C语言】【Leetcode】2437. 有效时间的数目

文章目录


题目

链接: link


思路一、枚举

这题的可以简单的看成 h1 h2 : m1 m2 的情况,其中 h1 和 h2 有关, m1 和 m2 有关,数目不多可以直接暴力枚举解决

csharp 复制代码
int countTime(char * time) {
    int countHour = 0;
    int countMinute = 0;
    for (int i = 0; i < 24; i++) {
        int hiHour = i / 10;
        int loHour = i % 10;
        if ((time[0] == '?' || time[0] == hiHour + '0') && 
            (time[1] == '?' || time[1] == loHour + '0')) {
            countHour++;
        }
    } 
    for (int i = 0; i < 60; i++) {
        int hiMinute = i / 10;
        int loMinute = i % 10;
        if ((time[3] == '?' || time[3] == hiMinute + '0') && 
            (time[4] == '?' || time[4] == loMinute + '0')) {
            countMinute++;
        }
    }
    return countHour * countMinute;
}

由于时钟的最大值为 24,分钟的最大值为 60,在此题解中分别枚举所可能的时钟,以及所有可能分钟,时间复杂度为 O(24+60)=O(1)。

只要理清楚还是很好做的


思路二、回溯

由于当出现 '?' 时,我们可以填入 0 - 9 任意一个数字,然后再返回去看是否合法就行。

即 00<= h1h2 <=23 、 00<= m1m2 <=59

csharp 复制代码
bool check(const char *time) {
    //atoi提取数字,遇到非数字时停止
    int h1h2 = atoi(time);
    int m1m2 = atoi(time + 3);
    if (h1h2 < 24 && m1m2 < 60) {//正常读取时不会出现负号,所以无所谓>=0
        return true;
    } else {
        return false;
    }
}

void dfs(char *time, int pos, int *res) {
    if (time[pos] == '\0') {//每次循环到结尾才去看这时是否合法
        if (check(time)) {
            (*res)++;
        }
        return;
    }
    if (time[pos] == '?') {
        for (int i = 0; i <= 9; i++) {
            time[pos] = '0' + i;
            dfs(time, pos + 1, res);
            time[pos] = '?';
        }
    } else {
        dfs(time, pos + 1, res);
    }
}

int countTime(char * time){
    int res = 0;//记录可能性
    dfs(time, 0, &res);
    return res;
}
相关推荐
Navigator_Z8 小时前
LeetCode //C - 1289. Minimum Falling Path Sum II
c语言·算法·leetcode
himobrinehacken8 小时前
取模运算的汇编奥秘揭秘
c语言·安全
mmmmath_38 小时前
LeetCode.104.二叉树的最大深度
数据结构·leetcode
青岚_Nox11 小时前
C语言实战:带你手写一个带"计时功能"的猜数字小游戏
c语言
Tisfy13 小时前
LeetCode 2333.最小差值平方和:排序 + 数学计算(不用二分)
数学·算法·leetcode·题解·贪心·排序
aqiu11111113 小时前
【C++算法打怪专栏】LeetCode 217. 存在重复元素(解法总结)
c++·算法·leetcode
iotxiaohu13 小时前
用 cflow 查看 C 函数调用关系
c语言·开发语言·cflow
yi01114 小时前
DAY28: LeetCode 111. 二叉树的最小深度
人工智能·笔记·python·算法·leetcode·二叉树·递归
局部有解15 小时前
Leetcode Hot100 - 最长连续序列
算法·leetcode·职场和发展
iCxhust15 小时前
51单片机电力载波应用开发(九)51产品化
c语言·数据库·嵌入式硬件·mysql·51单片机·软件工程·c51