-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path140.cpp
57 lines (55 loc) · 1.54 KB
/
140.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//
// 140.cpp
// leetcode
//
// Created by R Z on 2018/5/14.
// Copyright © 2018年 R Z. All rights reserved.
//
#include <stdio.h>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> res;
if(s==""||wordDict.size()==0) return res;
vector<bool> dp(s.length()+1, false);
dp[0]=true;
unordered_set<string> st;
for(string str: wordDict) st.insert(str);
for(int i=1; i<s.length(); i++){
for(int j=i-1;j>=0;j--){
if(dp[j]){
if(st.find(s.substr(j,i-j))!=st.end()){
dp[i]=true;
break;
}
}
}
}
if(!dp[s.length()]) return res;
string tmp="";
backtrack(s,st,res,tmp,0);
return res;
}
void backtrack(string s, unordered_set<string> &st, vector<string> &res, string tmps,int start){
if(s.length()==start){
res.push_back(tmps);
return;
}
else{
for(int i=start+1;i<=s.length();i++){
string word=s.substr(start,i-start);
if(st.find(word)!=st.end()){
string stmp=tmps;
if(start==0) tmps=word;
else tmps=tmps+" "+word;
backtrack(s,st,res,tmps,i);
tmps=stmp;
}
}
}
}
};