Description
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.
24-hour times are formatted as “HH:MM”, where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
Return the latest 24-hour time in “HH:MM” format. If no valid time can be made, return an empty string.
Example 1:
Input: A = [1,2,3,4]
Output: "23:41"
Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.
Example 2:
Input: A = [5,5,5,5]
Output: ""
Explanation: There are no valid 24-hour times as "55:55" is not valid.
Example 3:
Input: A = [0,0,0,0]
Output: "00:00"
Example 4:
Input: A = [0,0,1,0]
Output: "10:00"
Constraints:
- arr.length == 4
- 0 <= arr[i] <= 9
分析
题目的意思是:给定4个数,求能够组成的最大时间点的数。这道题我最先想到的是用递归,把所有的组合列举出来,选出合法的最大时间点就行了,遍历的时候用visited记录遍历过的点。这道题我看答案用的是暴力求解,调用了permutations函数,也可以。
代码
class Solution:
def solve(self,arr,ans,visited):
if(len(ans)==len(arr)):
h=ans[0]*10+ans[1]
s=ans[2]*10+ans[-1]
if(h<24 and s<=59):
if(self.max_hour<h):
self.max_hour=h
self.max_sec=s
elif(self.max_hour==h and self.max_sec<s):
self.max_sec=s
return
for i in range(len(arr)):
if(visited[i]==False):
visited[i]=True
ans.append(arr[i])
self.solve(arr,ans,visited)
ans.pop()
visited[i]=False
def largestTimeFromDigits(self, arr: List[int]) -> str:
n=len(arr)
min_val=min(arr)
self.max_hour=-1
self.max_sec=-1
visited=[False]*4
self.solve(arr,[],visited)
if(self.max_hour==-1):
return ''
return "{:02d}:{:02d}".format(self.max_hour, self.max_sec)