leetcode dp wordbreakII

#include <iostream>
#include<vector>
#include <string>
#include<map>
#include <stdlib.h>
using namespace std;
/*
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"].
*/

vector<string>nums;
bool isValid(string *dict,int len,string str)
{
    for (int i = 0; i < len; ++i)
    {
        if (dict[i] == str)return true;
    }
    return false;
}
void dfs(vector<vector<bool>>dp,int N,string str,int index,string path)
{
    if (index>N)return;
    if (index == N)
    {
        nums.push_back(path);
        return;
    }
    for (int i = index; i < N; ++i)
    {
        if (dp[index][i])
        {
            string tmp = path;
            if (path.size()==0)
                path = str.substr(index, i - index + 1);
            else
            path = path + " " + str.substr(index, i - index + 1);
            dfs(dp, N, str, i + 1, path);
            path = tmp;
            
        }
    }
}
int main()
{
    string str="catsanddogcatsand";
    int N = str.size();
    string dict[5] = { "cat", "cats", "and", "sand", "dog" };
    vector<vector<bool>>dp(N,vector<bool>(N,false));
    for (int i = 0; i < N; i++)
    {
        for (int j = i; j < N; j++)
        {
            if (isValid(dict, 5, str.substr(i, j - i + 1)))
            {
                dp[i][j] = true;
            }
        }
    }
    dfs(dp,N,str,0,"");
    cout << nums.size() << endl;
    for (int i = 0; i < nums.size(); ++i)
    {
        cout << nums[i] << endl;
    }
    cin.get();
    return 0;
}

 

posted @ 2016-08-25 09:16  mahaitao617  阅读(218)  评论(0编辑  收藏  举报