2019.7.29(动态规划)
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.
import java.util.*; public class Solution { ArrayList<String> list = new ArrayList<String>(); public ArrayList<String> wordBreak(String s, Set<String> dict) { dfs(s , dict , "" , s.length()); return list; } public void dfs(String s , Set<String> dict , String str , int index){ if(index <= 0){ if(str.length() > 0){ list.add(str.substring(0 , str.length() - 1)); } } for(int i = index;i >= 0 ;i--){ if(dict.contains(s.substring(i , index))){ dfs(s , dict , s.substring(i , index) + " " + str , i); } } } }