[Leetcode] Word Break II (Java)

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

找到所有拆分组合

DFS遗憾的又超时了,要保存下中间结果,DP用map找到有解后续节点list,然后DFS输出所有解

public class Solution {
    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        
		ArrayList<String> ret = new ArrayList<String>();
		Map<Integer,List<Integer>> map = new HashMap<Integer, List<Integer>>();
		
		buildPos(s, dict, map);
		
	    if(map.get(0)==null)
			return ret;
			
		print(s,map,ret,"",0);
		
		return ret;
	}
	private void print(String s, Map<Integer, List<Integer>> map,ArrayList<String> ret,String tmp,int pos) {
	    
		if(pos==s.length()){
			ret.add(tmp.substring(0, tmp.length()-1));
			return;
		}
		
		List<Integer> list = map.get(pos);
		
		for(int i : list){
			print(s, map, ret, tmp+s.substring(pos,i)+" ",i);
		}
	}
	private void buildPos(String s, Set<String> dict,Map<Integer,List<Integer>> map){
	    
		List<Integer> list = new ArrayList<Integer>();
		
		for(int i=s.length()-1;i>=0;i--){
		    
			for(int j=list.size()-1;j>=0;j--){
			    
				if(dict.contains(s.substring(i, list.get(j)))){
					List<Integer> tmp = map.get(i);
					if(tmp==null){
						tmp=new ArrayList<Integer>();
						map.put(i,tmp);
					}
					tmp.add(list.get(j));
				}
			}
			
			if(dict.contains(s.substring(i))){
				List<Integer> tmp = map.get(i);
				if(tmp==null){
					tmp=new ArrayList<Integer>();
					map.put(i,tmp);
				}
				tmp.add(s.length());
			}
			
			List<Integer> tmp = map.get(i);
			if(tmp!=null)
				list.add(i);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值