leetcode轮回计划20181027

在本期的轮回计划中遇到了第一道最短路问题127,用的是SPFA来解

  1. 121 Best Time to Buy and Sell Stock
    题意:允许买卖一次
  2. 122 Best Time to Buy and Sell Stock II
    题意:允许买卖任意次
  3. 125 Valid Palindrome
    题意:判断给定字符串是不是回文,不考虑空格和标点,忽略大小写
  4. 127 Word Ladder
    题意:给定一个vector作为单词字典,给定一个开始单词和结束单词,返回从开始单词到结束单词的最短路径长度。
    思路:涉及到图的最短路,答案:
class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector& wordList) {
        
        int size = wordList.size();
        vector> edge(size + 2,vector());
        bool flag = false;
        
        if(diff(beginWord,endWord) == 1) return 2;
        
        for(int i = 0;i < size;++ i){
            for(int j = i;j < size;++ j){
                if(diff(wordList[i],wordList[j]) == 1){
                    edge[i].push_back(j);
                    edge[j].push_back(i);
                }
                //beginWord : size ; endWord : size + 1
                if(diff(wordList[i],beginWord) == 1){
                    edge[size].push_back(i);
                }
                int toEnd = diff(wordList[i],endWord);
                // cout< que;
        que.push(size);
        vector dis(size + 2,(1LL << 31) - 1);
        dis[size] = 1;
        for(;!que.empty();que.pop()){
            int n = que.front();
            int d = dis[n];
            //松弛
            for(auto point : edge[n]){
                if(dis[point] > d + 1){
                    dis[point] = d + 1;
                    que.push(point);
                    if(point == size + 1) return dis[point];
                }
            }
        }
        return 0;
    }
    int diff(string & begin,string &end){
        int ret = 0;
        int i = 0;
        while(i < begin.size()){
            if(begin[i] != end[i]) ret ++;
            i ++;
        }
        return ret;
    }
};
  1. 129 Sum Root to Leaf Numbers
    题意:使用每条根节点到叶节点的路径表示一个数字,给出这些数字的和
    思路:分治
  2. 130 Surrounded Regions
    题意:将不与边界相连接的区域覆盖
    思路:queue

你可能感兴趣的:(leetcode轮回计划20181027)