【LeetCode】126. 单词接龙 II 结题报告 (C++)

原题地址:https://leetcode-cn.com/problems/word-ladder-ii/description/

题目描述:

给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则:

每次转换只能改变一个字母。
转换过程中的中间单词必须是字典中的单词。
说明:

如果不存在这样的转换序列,返回一个空列表。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:

输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

输出:
[
  ["hit","hot","dot","dog","cog"],
  ["hit","hot","lot","log","cog"]
]
示例 2:

输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

输出: []

解释: endWord "cog" 不在字典中,所以不存在符合要求的转换序列。

 

解题方案:

不会,留着以后学。。

class Solution {
public:
    bool differ_one(string &s, string &t) {
        int n = 0;
        for (int i = 0; i < s.size(); ++i)
            if ((n += s[i] != t[i]) > 1) return false;
        return n == 1;
    }
    vector<vector<int>> fa;//fa[1]有元素x,代表wordList[1]由wordList[x]转化过来
    vector<string> tmp;
    vector<vector<string>> ans;
    void dfs(int index, vector<string>& wordList) {
        if (fa[index].empty()) {
            reverse(tmp.begin(), tmp.end());
            ans.push_back(tmp);
            reverse(tmp.begin(), tmp.end());
        }
        for (auto &x : fa[index]) {
            tmp.push_back(wordList[x]);
            dfs(x, wordList);
            tmp.pop_back();
        }
    }
    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {

        int b = -1, e = -1, x;
        for (int i = 0; i < wordList.size(); ++i) {
            if (wordList[i] == beginWord) b = i;
            if (wordList[i] == endWord) e = i;
        }
        if (e == -1) return ans;
        if (b == -1) wordList.push_back(beginWord), b = wordList.size() - 1;
        queue<int> que;
        fa.assign(wordList.size(), vector<int>());
        vector<int> index(wordList.size(), 0);//index代表第几层
        que.push(b), index[b] = 1;//b是端点
        while (!que.empty()) {
            x = que.front(), que.pop();
            if (index[e] && index[x] >= index[e]) break;
            for (int i = 0; i < wordList.size(); ++i)
                if ((index[i] == 0 || index[x] + 1 == index[i]) && differ_one(wordList[x], wordList[i]))
                    if (index[i] == 0) index[i] = index[x] + 1, que.push(i), fa[i].push_back(x);
                    else fa[i].push_back(x);
        }
        if (index[e] == 0) return ans;
        tmp.push_back(endWord);
        dfs(e, wordList);
        tmp.pop_back();
        return ans;
    }

};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值