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
| vector<string> res; unordered_map<int, int> hashdata = {{0,1},{1,2},{2,4},{3,8},{4,1},{5,2},{6,4},{7,8},{8,16},{9,32}}; void backtrack(int num,int start,pair<int,int>& time){ // 结束条件 if(num == 0) { if(time.first > 11 || time.second > 59) { return; } string temp_hour = to_string(time.first); string temp_minute = to_string(time.second); if(temp_minute.size() == 1) { temp_minute.insert(0, "0"); } res.push_back(temp_hour + ":" + temp_minute); return; } for(int i = start; i < 10; i++) { if(time.first > 11 || time.second > 59) { continue; } // 在本层中创建一个变量store用来存储当前的time值,回退时使用 pair<int, int> store = time; if(i < 4) { time.first += hashdata[i]; } else { time.second += hashdata[i]; } backtrack(num - 1, i + 1, time); // 在同层回退时把前面存好的store再赋给time,时time恢复到原状态 time = store; } }
vector<string> readBinaryWatch(int num) { pair<int, int> time(0, 0); backtrack(num, 0, time); return res; }
|