Skip to content

Commit

Permalink
dfs, corrected from above
Browse files Browse the repository at this point in the history
  • Loading branch information
keineahnung2345 authored Oct 21, 2020
1 parent 7d7a050 commit b35b216
Showing 1 changed file with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,59 @@ class Solution {
}
};

//dfs, corrected from above
//Runtime: 592 ms, faster than 29.07% of C++ online submissions for Lexicographically Smallest String After Applying Operations.
//Memory Usage: 169.2 MB, less than 5.03% of C++ online submissions for Lexicographically Smallest String After Applying Operations.
class Solution {
public:
int n;
unordered_set<string> visited;
unordered_map<string, string> memo;

string add(string& s, int a){
string ret = s;
for(int i = 1; i < n; i+=2){
ret[i] = '0'+(ret[i]-'0'+a)%10;
}
return ret;
}

string rotate(string& s, int b){
string ret = s;

ret = s.substr(b) + s.substr(0, b);

return ret;
}

string dfs(string& s, int& a, int& b){
if(memo.find(s) != memo.end()){
// cout << "memo" << endl;
return memo[s];
}else if(visited.find(s) != visited.end()){
//to jump out of the loop!
return "aaaa";
}else{
visited.insert(s);
string sadd = add(s, a);
string srot = rotate(s, b);

// cout << s << ", add: " << sadd << ", rot: " << srot << endl;

memo[s] = min({s, dfs(sadd, a, b), dfs(srot, a, b)});

// cout << s << " -> " << memo[s] << endl;
return memo[s];
}
}

string findLexSmallestString(string s, int a, int b) {
n = s.size();

return dfs(s, a, b);
}
};

//dfs
//https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/discuss/899489/Basic-DFS-Brute-force-or-This-kind-of-questions-DFS
//no early stop make it correct?
Expand Down

0 comments on commit b35b216

Please sign in to comment.