[LeetCode] Word Break II

题目链接:https://oj.leetcode.com/problems/word-break-ii/

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递归遍历。采用动态规划比较麻烦,需要存储当前位置能够实现 word break的所有结果的和,空间复杂度很高,不划算,代码写起来还很麻烦。

public class Solution {
    public List<String> wordBreak(String s, Set<String> dict) {
        List<String> rsList = new ArrayList<String>();
        if (s == null || s.length() < 1 || dict == null) {
            return rsList;
        }
        
        wordBreakHelper(s, 0, "", dict, rsList);
        
        return rsList;
    }
    
    public void wordBreakHelper(String s, int start, String tempStr, Set<String> dict, List<String> rsList)  {
        if (start >= s.length()) {
            rsList.add(tempStr);
            return;
        }
        
        for (int i = start + 1; i <= s.length(); i++) {
            String temp = s.substring(start, i);
            if (dict.contains(temp)) {
                String newTempStr;
                if (tempStr.length() < 1) {
                    newTempStr = temp;
                } else {
                    newTempStr = tempStr + " " + temp;
                }
                
                wordBreakHelper(s, i, newTempStr, dict, rsList);
            }
        }
    }
}

用这个方法还是有一个结果TLE,将WordBreak的方法放到前面先判断一下是否能够word break 后再进行下面的程序就可以AC

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值