-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
46 lines (40 loc) · 1.37 KB
/
Solution.java
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
// https://leetcode.com/problems/word-break-ii
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
ArrayList<String> [] pos = new ArrayList[s.length()+1];
pos[0]=new ArrayList<String>();
for(int i=0; i<s.length(); i++){
if(pos[i]!=null){
for(int j=i+1; j<=s.length(); j++){
String sub = s.substring(i,j);
if(wordDict.contains(sub)){
if(pos[j]==null){
ArrayList<String> list = new ArrayList<String>();
list.add(sub);
pos[j]=list;
}else{
pos[j].add(sub);
}
}
}
}
}
if(pos[s.length()]==null){
return new ArrayList<String>();
}else{
ArrayList<String> result = new ArrayList<String>();
dfs(pos, result, "", s.length());
return result;
}
}
public void dfs(ArrayList<String> [] pos, ArrayList<String> result, String curr, int i){
if(i==0){
result.add(curr.trim());
return;
}
for(String s: pos[i]){
String combined = s + " "+ curr;
dfs(pos, result, combined, i-s.length());
}
}
}