LeetCode 高级 - 单词拆分 II

单词拆分 II

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:

  • 分隔时可以重复使用字典中的单词。
  • 你可以假设字典中没有重复的单词。

示例 1:

输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
  "cats and dog",
  "cat sand dog"
]

示例 2:

输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。

示例 3:

输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]

分析

核心就是 DP + DFS

利用 单词划分 的 DP 方法判断是否能够成功划分,能划分则利用 DFS 确定划分情况。

参考网上的思路,若不剪枝,直接 DFS 会 TLE

代码

class Solution {
    //DP + DFS
    public List<String> wordBreak(String s, List<String> wordDict) {

        List<String> res = new ArrayList<String>();

        //dp 判断能否拆分
        boolean[] dp = new boolean[s.length()+1];
        dp[0] = true;
        for(int i=0 ;i<=s.length();i++){
          for(int j=0;j<i;j++){
              if(dp[j] && wordDict.contains(s.substring(j,i))){
                  dp[i]=true;
                  break;
              }
          }
        }

        if(!dp[s.length()]){
            return res;
        }

        StringBuilder sb = new StringBuilder();
        dfs(s,wordDict,sb,res,0);
        return res;
    }

    private void dfs(String s,List<String> wordDict,StringBuilder sb,List<String> res,int start){

        if(start == s.length()){
            res.add(sb.toString().trim());
            return;
        }

        for(int i=start+1;i<=s.length();i++){
            String str = s.substring(start,i);
            if(wordDict.contains(str)){
                int length = sb.length();
                sb.append(str).append(" ");
                dfs(s,wordDict,sb,res,i);
                sb.setLength(length);
            }
        }

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值