forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cpp
31 lines (29 loc) · 891 Bytes
/
Solution2.cpp
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
class Solution {
public:
int ans;
string seq = "ACGT";
int minMutation(string start, string end, vector<string>& bank) {
unordered_set<string> s;
for (auto& b : bank) s.insert(b);
ans = INT_MAX;
s.erase(start);
dfs(start, end, s, 0);
return ans == INT_MAX ? -1 : ans;
}
void dfs(string& start, string& end, unordered_set<string>& s, int t) {
if (start == end) {
ans = min(ans, t);
return;
}
for (int i = 0; i < start.size(); ++i) {
for (char& c : seq) {
if (start[i] == c) continue;
string nxt = start.substr(0, i) + c + start.substr(i + 1, start.size() - i - 1);
if (s.count(nxt)) {
s.erase(nxt);
dfs(nxt, end, s, t + 1);
}
}
}
}
};