leetcode 22. 单词转换

给定字典中的两个词,长度相等。写一个方法,把一个词转换成另一个词, 但是一次只能改变一个字符。每一步得到的新词都必须能在字典中找到。

编写一个程序,返回一个可能的转换序列。如有多个可能的转换序列,你可以返回任何一个。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-transformer-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 主要采用回溯算法,逐个查找

class Solution {
public:
    bool Translation(const string& a, const string& b)
    {
        if (a.size() != b.size()) {
            return false;
        }
        int cnt = 0;
        for (size_t i = 0; i < a.size(); ++i) {
            if (a[i] != b[i]) {
                cnt++;
            }
            if (cnt >= 2) {
                return false;
            }

        }
        return cnt == 1 ? true : false;
    }

    bool find(string beginWord, string endWord, vector<string>& wordList, vector<bool>& visited, vector<string>& path)
    {
        if (std::equal(beginWord.begin(), beginWord.end(), endWord.begin())) {
            return true;
        }
        for (size_t i = 0; i < wordList.size(); ++i) {
            if (visited[i] || !Translation(beginWord, wordList[i])) {
                continue;
            }
            // 标记已经访问过
            visited[i] = true;
            path.push_back(wordList[i]);
            if (find(wordList[i], endWord, wordList, visited, path)) {
                return true;
            }
            path.pop_back();
        }
        return false;
    }

    vector<string> findLadders(string beginWord, string endWord, vector<string>& wordList)
    {
        vector<bool> visited(wordList.size(), false);
        vector<string> path;
        path.push_back(beginWord);
        if (find(beginWord, endWord, wordList,visited, path)) {
            return path;
        }
        return vector<string> {};
    }
    void ShowPath(const vector<string>& path)
    {
        cout << ".......begin....." << endl;
        for (size_t i = 0; i < path.size(); ++i) {
            cout << path[i] << endl;
        }
        cout << ".......end....." << endl;
    }
};

 

posted on 2022-04-07 19:50  蜀山菜鸟  阅读(109)  评论(0)    收藏  举报