• [LeetCode]Word Break


    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

    For example, given
    s = "leetcode",
    dict = ["leet", "code"].

    Return true because "leetcode" can be segmented as "leet code".

    思路:回溯+递归=超时

     1 class Solution {
     2 public:
     3     bool wordBreak(string s, unordered_set<string> &dict) {
     4         if(dict.find(s)!=dict.end()) return true;
     5         int len=s.size();
     6         for(int i=1;i<=len;i++)
     7         {
     8             if(dict.find(s.substr(0,i))!=dict.end())
     9             {
    10                 string str=s.substr(i,len-i);
    11                 //return wordBreak(str,dict);
    12                 if(wordBreak(str,dict)) return true;
    13             }
    14         }
    15         return false;
    16     }
    17 };
    View Code

    备忘录法,记忆化搜索。

    class Solution {
    public:
        bool wordBreak(string s, unordered_set<string> &dict) {
            if(dict.find(s)!=dict.end()) return true;
            int len=s.size();
            vector<bool> dp(len+1,false);
            dp[0]=true;
            for(int i=1;i<=len;i++)
            {
                for(int j=0;j<i;j++)
                {
                    if(dp[i]=dp[j]&&(dict.find(s.substr(j,i-j))!=dict.end()))
                        break;
                }
            }
            return dp[len];
        }
    };
    

      

  • 相关阅读:
    函数
    特殊集合
    集合
    数组复习
    数组
    IPython--转
    python 单例模式总结
    拼多多笔试题
    python 创建实例--待完善
    转--算法时间复杂度
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3508915.html
Copyright © 2020-2023  润新知