easy to understand c++ solution, looking for optimization


  • 0
    A
    public:
        int minMutation(string start, string end, vector<string>& bank) {
            int count = 0;
            unordered_set<string> dictionary;
            dictionary.insert(bank.begin(), bank.end());
            if(!dictionary.count(end))
                return -1;
            vector<int> difference;
            for(int i = 0; i < start.size(); i++)
            {
                if(start[i] != end[i])
                    difference.push_back(i);
            }
            if(helper(start, end, difference, dictionary, difference.size()))
                return difference.size();
            else
                return -1;
            
        }
        bool helper(string word, string end, vector<int>& difference, unordered_set<string>& dictionary, int n)
        {
            if(n == 0)
                return true;
            for(int i = 0; i < difference.size(); i++)
            {
                string temp = word;
                temp[difference[i]] = end[difference[i]];
                if(dictionary.count(temp))
                {
                    return helper(temp, end, difference, dictionary, n-1);
                }
            }
            return false;
        }
    };```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.