题目大意:
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
 你可以假设字典中没有重复的单词。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
 输出: true
 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
 示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
 输出: true
 解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。 注意你可以重复使用字典中的单词。
 示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
 输出: false
解题思路:
第一种是搜索的思路,使用BFS,每次我们队列push单词的起始搜索位置,然后枚举单词结束的位置,用hash表来存字典,看字典中是否存在这一个单词,存在的话开始下一个位置查找。为了避免搜索同一个位置,可以打一个标志数组dp,大家可以试一下不用这个标志数组运行速度是否有差异。
class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        queue<int> q;
        int u = 0;
        vector<int> dp;
        dp.assign(s.size()+10,0);
        q.push(u);
        unordered_set<string> ms;
        for(auto it:wordDict)ms.insert(it);
        while(!q.empty()){
            int u = q.front();q.pop();
            if(u == s.size())return true;
            for(int i = u;i<(int)s.size();i++){
                if(ms.count(s.substr(u,i-u+1))){
                    if(dp[i+1])continue;
                    dp[i+1] = 1;
                    q.push(i+1);
                }
            }
        }
        return false;
    }
};第二种思路:
假设dp[n]为s字符串的第n位是否可行,我们得到转移方程为:
for( i = 0 ;i<dict.size();i++)
if(s contain word word[i] from n position)
dp[n] |= dp[n+word[i].length()]
class Solution {
public:
    vector<int> dp;
    string str;
    vector<string> arrmv;
    int N;
    bool dfs(int n ){
        
        if(n == N)return 1;
        if(dp[n]!=-1)return dp[n];
        int ret = 0;
        for(int i = 0;i<(int)arrmv.size();i++){
            int len2 = arrmv[i].size();
            
            if(n+len2-1<=N-1 ){
                int suc = 1;
                for(int j = 0;j<len2;j++)if(arrmv[i][j]!=str[n+j])suc = 0;
                
                if(suc)ret|=dfs(n+len2);
            }
            
        }
        return dp[n] = ret;
    }
    bool wordBreak(string s, vector<string>& wordDict) {
        str= s;
        N=str.size();
        arrmv=wordDict;
        dp.assign(s.size()+1,-1);
        return dfs(0);
    }
};










