-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-watch.cpp
More file actions
55 lines (45 loc) · 1.41 KB
/
binary-watch.cpp
File metadata and controls
55 lines (45 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// Created by darion.yaphet on 2025/6/29.
//
#include <vector>
using namespace std;
// https://leetcode.cn/problems/binary-watch/description
class Solution {
private:
vector<string> result;
// 小时和分钟对应的权重值
vector<int> hourWeights = {1, 2, 4, 8};
vector<int> minuteWeights = {1, 2, 4, 8, 16, 32};
public:
vector<string> readBinaryWatch(int turnedOn) {
vector<int> led(10, 0); // 10 个灯,默认都是灭的
backtrack(led, 0, turnedOn);
return result;
}
void backtrack(vector<int> &led, int start, int left) {
if (left == 0) {
// 所有灯都已选完,计算时间
int hour = 0, minute = 0;
for (int i = 0; i < 4; ++i) {
if (led[i]) {
hour += hourWeights[i];
}
}
for (int i = 4; i < 10; ++i) {
if (led[i]) {
minute += minuteWeights[i - 4];
}
}
if (hour <= 11 && minute <= 59) {
string time = to_string(hour) + ":" + (minute < 10 ? "0" : "") + to_string(minute);
result.push_back(time);
}
return;
}
for (int i = start; i < 10; ++i) {
led[i] = 1; // 选择这个位置点亮
backtrack(led, i + 1, left - 1);
led[i] = 0; // 撤销选择
}
}
};