2375: Construct-Smallest-Number-From-DI-String
Medium
Week of backtracking!
My initial solution was quite brute-force, just recursively iterating through all the minimum values, until we stumble upon a solution.
Code:
class Solution {
public:
bool recursion(int index, string pattern, string& ans, int *num) {
if (index == pattern.size()+1) {
return true;
}
for (int i = 1; i < 10; ++i) {
if (num[i] == 1) continue;
if (index > 0 and (pattern[index-1] == 'I' ? ans[ans.size()-1]-'0' > i : ans[ans.size()-1]-'0' < i)) continue;
[i] = 1;
num+= char(i+'0');
ans if (recursion(index+1, pattern, ans, num)) {
return true;
}
.pop_back();
ans[i] = 0;
num}
return false;
}
(string pattern) {
string smallestNumberint num[10] = {0};
= "";
string ans (0, pattern, ans, num);
recursionreturn ans;
}
};
Complexity:
I realised that there was a much simpler intuitive way of writing the solution.
Code:
class Solution {
public:
(string pattern) {
string smallestNumber= "";
string ans for (int i = 0; i <= pattern.size(); ++i) {
int num = i+1;
while (pattern[i] == 'I') {
+= num++ +'0';
ans ++i;
}
int counter = 0;
while (pattern[i] == 'D') {
++counter;
++i;
++num;
}
++counter;
while (counter--) {
+= num-- +'0';
ans }
}
return ans;
}
};