949. Largest Time for Given Digits

思路

其实这个思路挺简单的,就搜索全排列,然后找到合法的最大值即可。
但是自己写出来的代码和别人写出来的代码还是有差别的,所以还是记录下。

代码

  • 我的代码

    1. class Solution {
    2. public:
    3. vector<bool> st;
    4. int path;
    5. int ans = -1;
    6. void dfs(vector<int> &arr, int depth) {
    7. if (depth == 4) {
    8. ans = max(ans, path);
    9. return;
    10. }
    11. for (int i = 0; i < 4; i ++) {
    12. if (st[i]) {
    13. continue;
    14. }
    15. path = path * 10 + arr[i];
    16. if (depth == 1) {
    17. if (path >= 24) {
    18. path = path / 10;
    19. continue;
    20. }
    21. }
    22. if (depth == 3) {
    23. if (path % 100 >= 60) {
    24. path = path / 10;
    25. continue;
    26. }
    27. }
    28. st[i] = true;
    29. dfs(arr, depth + 1);
    30. path = path / 10;
    31. st[i] = false;
    32. }
    33. }
    34. string largestTimeFromDigits(vector<int>& arr) {
    35. st = vector<bool>(4, false);
    36. path = 0;
    37. dfs(arr, 0);
    38. if (ans == -1) {
    39. return "";
    40. }
    41. string hour = to_string(ans / 100);
    42. if (hour.size() < 2) {
    43. hour = "0" + hour;
    44. }
    45. string minute = to_string(ans % 100);
    46. if (minute.size() < 2) {
    47. minute = "0" + minute;
    48. }
    49. return hour + ":" + minute;
    50. }
    51. };
  • 别人的代码

  • 这个地方要注意,必须要排序,next_permutation返回比当前大的一个排列。
  • 另外就是你是用的int,但其实用string也完全OK的。
    1. class Solution {
    2. public:
    3. string largestTimeFromDigits(vector<int>& arr) {
    4. sort(arr.begin(), arr.end());
    5. string res;
    6. do {
    7. string h = to_string(arr[0]) + to_string(arr[1]);
    8. string m = to_string(arr[2]) + to_string(arr[3]);
    9. if (h <= "23" && m <= "59") {
    10. string temp = h + ":" + m;
    11. if (res.empty() || res < temp) {
    12. res = temp;
    13. }
    14. }
    15. } while(next_permutation(arr.begin(), arr.end()));
    16. return res;
    17. }
    18. };