zoukankan      html  css  js  c++  java
  • 【leetcode】Word Break II

    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"].

     
    与Word Break I类似,只不过需要把所有情况都表示出来。
    首先利用Word Break I中的动态规划
     
    dp[i]=true 代表了0,1,...,i-1可以用字典中的元素分割
    同时新建一个map<int,vector<int>> slice,用于记录分割的位置
    如slice[i]=j代表了0,1,...,i-1可以分割为0,1,j-1和j,j+1,...,i-1
     
    利用这个slice,利用dfs便可以找到所有的结果
      
     
     1 class Solution {
     2 public:
     3     vector<string> wordBreak(string s, unordered_set<string> &dict) {
     4        
     5  
     6         vector<bool> dp(s.length()+1);
     7         dp[0]=true;
     8         map<int,vector<int> > slice;
     9            
    10         // dp[i]  0,1,2...i-1可以被分割
    11         // hash[i]=j 表示0,1,2...i-1可以分割为0,1,2,...,j-1和j,j+1,...,i
    12         for(int i=1;i<s.length()+1;i++)
    13         {
    14             for(int j=0;j<i;j++)
    15             {
    16                 if(dp[j]&&dict.count(s.substr(j,i-j)))
    17                 {
    18                     dp[i]=true;
    19                    
    20                     if(slice.find(i)!=slice.end()) slice[i].push_back(j);
    21                     else slice[i]=vector<int>(1,j);
    22                 }
    23             }
    24         }
    25        
    26         vector<string> result;
    27        
    28         dfs(result,slice,s.length(),s,s);
    29         return result;
    30     }
    31    
    32     void dfs(vector<string> &result,map<int,vector<int>> &slice,int start,string &s,string cur)
    33     {
    34         if(start==0)
    35         {
    36            cur.erase(0,1);
    37            result.push_back(cur);
    38            return;
    39         }
    40        
    41         vector<int> sliceV=slice[start];
    42         for(int i=0;i<sliceV.size();i++)
    43         {
    44             string tmp=cur;
    45             cur.insert(sliceV[i]," ");
    46             dfs(result,slice,sliceV[i],s,cur);
    47             cur=tmp;
    48         }
    49     }
    50    
    51 };
     
  • 相关阅读:
    构造回文的最小插入次数
    动态规划设计:最大子数组
    状态压缩:对动态规划进行降维打击
    团灭 LeetCode 股票买卖问题
    经典动态规划:戳气球
    贪心算法之区间调度问题
    微信分享 添加URL Schemes
    UITouch的用法
    HTTP协议详解
    经典SQL语句大全
  • 原文地址:https://www.cnblogs.com/reachteam/p/4231074.html
Copyright © 2011-2022 走看看