全排列思想
class Solution {
public:
void is_valid(vector<int>& A, set<pair<int,int>> & valid) {
int first = A[0] * 10 + A[1];
int second = A[2] * 10 + A[3];
if (first < 24 && second < 60) {
valid.insert({first, second});
}
}
void dfs(vector<int>& A, set<pair<int,int>> & valid, int index) {
if (index >= 4) {
return;
}
for (int i=index; i<4; i++) {
swap(A[index], A[i]);
dfs(A, valid, index + 1);
is_valid(A, valid);
swap(A[index], A[i]);
}
}
string largestTimeFromDigits(vector<int>& A) {
sort(A.begin(), A.end());
string res;
set<pair<int,int>> valid;
dfs(A, valid, 0);
if (valid.size()) {
string tmp_1, tmp_2;
tmp_1 = to_string(valid.rbegin()->first);
tmp_2 = to_string(valid.rbegin()->second);
if (valid.rbegin()->first < 10) {
tmp_1 = "0" + tmp_1;
}
if (valid.rbegin()->second < 10) {
tmp_2 = "0" + tmp_2;
}
res = tmp_1+ ':' + tmp_2;
}
return res;
}
};