难度:简单。
标签:位运算,回溯算法。
这个题,错了好几次,开始传入choose的地址到getResult,其值可修改,导致错误。
之后一些细节导致错误。
可以将hour和minute分开进行回溯,这样效率会更高。
正确解法:
class Solution {
vector<string> results;
string getTime(vector<int> choose){
int h = 8 * choose[0] + 4 * choose[1] + 2 * choose[2] + choose[3];
int m = 32 * choose[4] + 16 * choose[5] + 8 * choose[6] + 4 * choose[7] + 2 * choose[8] + choose[9];
string str = "";
if(h < 12 && m < 60){
if(m < 10)str = to_string(h) + ":" + "0" + to_string(m);
else str = to_string(h) + ":" + to_string(m);
}
return str;
}
void getResult(int turnedOn, int k, vector<int> choose){
if(k >= 10)return;
if(turnedOn == 0){
string t = getTime(choose);
if(t != "")results.emplace_back(t);
return;
}
if(10 - k == turnedOn){
if(k <= 4)return;
for(int i = k; i < 10; ++i)choose[i] = 1;
string t = getTime(choose);
if(t != "")results.emplace_back(t);
return;
}
choose[k] = 1;
getResult(turnedOn - 1, k + 1, choose);
choose[k] = 0;
getResult(turnedOn, k + 1, choose);
}
public:
vector<string> readBinaryWatch(int turnedOn) {
if(turnedOn == 0){
return vector<string>{"0:00"};
}
else if(turnedOn > 8){
return vector<string>();
}
vector<int> choose(10, 0);
getResult(turnedOn, 0, choose);
return results;
}
};
结果: