2375.cpp (890B)
1 class Solution { 2 string crnt = string(9, '#'); 3 4 int rec(const string &pattern, uint mask = 0, uint idx = 0) { 5 if (idx == pattern.size() + 1) return 1; 6 7 int start, end; 8 if (!idx) { 9 start = 1; 10 end = 9; 11 } else { 12 if (pattern[idx - 1] == 'I') { 13 start = (crnt[idx - 1] & 0xF) + 1; 14 end = 9; 15 } else { 16 start = 1; 17 end = (crnt[idx - 1] & 0xF) - 1; 18 } 19 } 20 21 for (int i = start; i <= end; i++) { 22 if (mask & (1 << i)) continue; 23 crnt[idx] = '0' + i; 24 if (rec(pattern, mask | (1 << i), idx + 1)) return 1; 25 } 26 return 0; 27 } 28 29 public: 30 string smallestNumber(const string &pattern) { 31 crnt.resize(pattern.size() + 1); 32 rec(pattern); 33 return crnt; 34 } 35 };