zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    数据压缩API
    Dll劫持
    傀儡进程
    自定义网页右键菜单总结
    自定义checkbox, radio样式总结
    有趣的鼠标悬浮模糊效果总结
    听指令的小方块(二)总结
    听指令的小方块(一)总结
    表单(三)联动总结
    表单(二)多个表单项的动态校验总结
  • 原文地址:https://www.cnblogs.com/mahaitao/p/5805473.html
Copyright © 2011-2022 走看看