GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/code/lc140.java at master · mJackie/leetcode

Expand file tree

/

lc140.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
39 lines (37 loc) · 1.53 KB
/

lc140.java

Copy path

File metadata and controls

39 lines (37 loc) · 1.53 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package code;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/*
* 140. Word Break II
* 题意:给定词典,比照词典切字符串,能切出几种情况
* 难度:Hard
* 分类:Dynamic Programming, Backtracking
* 思路:回溯法
* Tips:和139做对比,因为需要每步骤返回值,所以递归的方法在这题更合适
*/
public class lc140 {
public List<String> wordBreak(String s, List<String> wordDict) {
List<String> res = new ArrayList<>();
if(s.length()==0) return res;
return helper(s, wordDict, new HashMap<>());
}
public List<String> helper(String s, List<String> wordDict, HashMap<String, List<String>> hm){
List<String> res = new ArrayList<>();
if(hm.containsKey(s)) return hm.get(s); //hm用以记录子结果,之前递归已计算出,则直接返回。备忘录算法。
for (int i = s.length()-1; i >=0 ; i--) {
String cut_str = s.substring(i);
if(wordDict.contains(cut_str)){
List<String> ls = helper(s.substring(0,i), wordDict, hm); //切掉以后剩下的字符串的结果
for(String str:ls){
res.add(str+" "+cut_str); //结果拼上切掉的字符串
}
if(i==0){ //切完了,不需要拼空格。hm中没有保存键值为""的,上个循环不会有效果。
res.add(cut_str);
}
hm.put(s, res);
}
}
return res;
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.