• leetcode126 Word Ladder II


    思路:

    宽搜过程中分层记录路径,递归还原。
    实现:

     1 class Solution 
     2 {
     3 public:
     4     void getPath(string now, string beginWord, string endWord, vector<string>& buf, unordered_map<string, unordered_set<string>>& par, vector<vector<string>>& ret)
     5     {
     6         if (now == beginWord)
     7         {
     8             vector<string> tmp(1, endWord);
     9             for (auto it : buf) tmp.push_back(it);
    10             ret.push_back(tmp);
    11             reverse(ret.back().begin(), ret.back().end());
    12             return;
    13         }
    14         for (auto it : par[now])
    15         {
    16             buf.push_back(it);
    17             getPath(it, beginWord, endWord, buf, par, ret);
    18             buf.pop_back();
    19         }
    20     }
    21     vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) 
    22     {
    23         unordered_set<string> tmp;
    24         for (auto it : wordList) tmp.insert(it);
    25         unordered_map<string, unordered_set<string>> par;
    26         unordered_set<string> q;
    27         q.insert(beginWord);
    28         bool flg = false;
    29         while (!q.empty())
    30         {
    31             unordered_set<string> next;
    32             for (auto it : q)
    33             {
    34                  for (int i = 0; i < it.length(); i++)
    35                 {
    36                     for (char c = 'a'; c <= 'z'; c++)
    37                     {
    38                         string buf = it;
    39                         if (buf[i] == c) continue;
    40                         buf[i] = c;
    41                         if (!tmp.count(buf)) continue;
    42                         if (!q.count(buf)) 
    43                         {
    44                             next.insert(buf);
    45                             par[buf].insert(it);
    46                         }
    47                         if (buf == endWord) flg = true;
    48                     }    
    49                 } 
    50             }
    51             for (auto it : q) { tmp.erase(it); }
    52             q = next;
    53             if (flg) break;
    54         }
    55         vector<vector<string>> ret;
    56         if (flg) 
    57         {
    58             vector<string> buf;
    59             getPath(endWord, beginWord, endWord, buf, par, ret);
    60         }
    61         return ret;
    62     }
    63 };
  • 相关阅读:
    Python 面向对象
    Python __str__()
    数据降维
    高并发相关概念
    centos7下安装kubernetes1.18
    OB-运行日志
    OB-租户(Tenant)管理
    OB-资源管理(Resource Unit/Pool)
    [转载]-基于 VMWARE Oracle Linux7.9 安装 Oracle19c RAC 详细配置方案
    OB-管理oceanbase集群参数
  • 原文地址:https://www.cnblogs.com/wangyiming/p/7518509.html
Copyright © 2020-2023  润新知