Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

思路:这道题是把s分解成任何可能的单词,并存在于dict中,而且可以组合成s。这依然使用动态规划,配合着DFS找到任何可能存在于dict中的子字符串。

Is[i]表示s[0,i)之间存在划分使分割后的字符串在dict里,赋值true,关于这一点可以看Word Break中的描述。至于dp[j][i]表示的是从j到i之间的字符是否存在于dict里。

class Solution {

public:

    void genWord(string &s,vector<vector<bool> > &dp,int index,vector<string> &path,vector<string> &result)

    {

        if(index==0)

        {

            string str;

            for(int i=path.size()-1;i>=0;i--)

            {

                str+=path[i];

                if(i!=0)

                {

                    str.push_back(' ');

                }

            }

            result.push_back(str);

        }

        for(int i=0;i<s.size();i++)

        {

            if(dp[i][index])

            {

                path.push_back(s.substr(i,index-i));

                genWord(s,dp,i,path,result);

                path.pop_back();

            }

        }

    }

    vector<string> wordBreak(string s, unordered_set<string> &dict) {

        int n=s.size();

        vector<string> result;

        result.clear();

        vector<string> mystring;

        mystring.clear();

        vector<vector<bool> > dp(n,vector<bool>(n+1,false));

        vector<bool> Is(n+1,false);

        Is[0]=true;

        if(n==0)

            return result;

        for(int i=1;i<=n;i++)

        {

            for(int j=i-1;j>=0;j--)

            {

                if(Is[j] && dict.find(s.substr(j,i-j))!=dict.end())

                {

                    Is[i]=true;

                    dp[j][i]=true;

                }

            }

        }

        genWord(s,dp,n,mystring,result);

        return result;

    }

};

 

你可能感兴趣的:(break)