949. 给定数字能组成的最大时间

给定一个由 4 位数字组成的数组,返回可以设置的符合 24 小时制的最大时间。

最小的 24 小时制时间是 00:00,而最大的是 23:59。从 00:00 (午夜)开始算起,过得越久,时间越大。

以长度为 5 的字符串返回答案。如果不能确定有效时间,则返回空字符串。

 

示例 1:

输入:[1,2,3,4]
输出:"23:41"

示例 2:

输入:[5,5,5,5]
输出:""

 

提示:

  1. A.length == 4
  2. 0 <= A[i] <= 9

 

class Solution {
public:
    string largestTimeFromDigits(vector<int>& A) {
        if (A.size() != 4) {
            return "";
        }
        string max_time = "";
        vector<bool> dict(A.size(), false);
        string temp;
        Permute(A, temp, 0, dict, max_time);
        return max_time;
    }
    void Permute(vector<int>& A, string& temp, int count, vector<bool>& dict, string& max_time) {
        if (count >= 4) {
            if (Valid(temp) && temp > max_time) {
                max_time = temp;
            }
            return ;
        }
        for (int i = 0; i < A.size(); ++i) {
            if (dict[i]) {
                continue;
            }
            dict[i] = true;
            temp.push_back(A[i] + '0');
            if (count == 1) {
                temp.push_back(':');
            }
            Permute(A, temp, count + 1, dict, max_time);
            temp.pop_back();
            if (count == 1) {
                temp.pop_back();
            }
            dict[i] = false;
        }
    }
    bool Valid(string& temp) {
        int hour = atoi(temp.substr(0, 2).c_str());
        int minute = atoi(temp.substr(3,2).c_str());
        if (hour > 23 || hour < 0 || minute < 0 || minute > 59) {
            return false;
        }
        return true;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值