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;
    }
  • 相关阅读:
    ubuntu安装后做得几件事情 【robby_chan】
    malloc函数的一种简单的原理性实现[转]
    了解B树 B+树
    win下格式转为utf8 编码 转码
    log4j2与slf4j日志桥接
    java获取当前行数
    java获取服务器ip地址解决linux上为127.0.0.1的问题
    log4j2的基本使用
    navicator使用之mysql
    log4j与log4j2日志文件的操作
  • 原文地址:https://www.cnblogs.com/mahaitao/p/5805473.html
Copyright © 2011-2022 走看看