题目描述:https://pycoder.blog.csdn.net/article/details/125114910
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_TIME (24 * 60)
int dp_valid_num;
int dp[4];
int source_time;
int time_tmp[4];
int time_res[4];
int min_time;
void dfs(int num)
{
if (num >= 4) {
int time_diff;
int time = (time_tmp[0] * 10 + time_tmp[1]) * 60 +
time_tmp[2] * 10 + time_tmp[3];
if ((time_tmp[0] * 10 + time_tmp[1]) > 24
|| (time_tmp[2] * 10 + time_tmp[3]) > 60
|| time == source_time
) return;
if (time >= source_time) {
time_diff = time - source_time;
} else {
time_diff = MAX_TIME - source_time + time;
}
if (time_diff < min_time) {
min_time = time_diff;
memcpy(time_res, time_tmp, sizeof(int) * 4);
}
return;
}
for (int i = 0; i < dp_valid_num; i++) {
time_tmp[num] = dp[i];
dfs(++num);
num--;
}
}
int main(void)
{
char str[10];
int hash[10] = {0};
min_time = MAX_TIME;
dp_valid_num = 0;
memset(dp, 0, sizeof(int) * 4);
scanf("%s", str);
hash[str[0] - '0'] = 1;
hash[str[1] - '0'] = 1;
hash[str[3] - '0'] = 1;
hash[str[4] - '0'] = 1;
source_time = ((str[0] - '0') * 10 + (str[1] - '0')) * 60 +
(str[3] - '0') * 10 + (str[4] - '0');
// 根据有效的数字进行dfs
for (int i = 0; i < 10; i++) {
if (hash[i] == 1) {
dp[dp_valid_num++] = i;
}
}
dfs(0);
printf("%d%d:%d%d\n", time_res[0], time_res[1], time_res[2], time_res[3]);
return 0;
}