回溯法 | 单词拆分 ||

class Solution {
    List<String> ss = new ArrayList<>();
    public List<String> wordBreak(String s, List<String> wordDict) {

        dfs(s,wordDict,"",0);

        return ss;
    }
    public void dfs(String s, List<String> wordDict, String res, int idx){
        if(idx==s.length()){
            ss.add(res.trim());
            return;
        }
        //去掉外循环
        for(int j=idx+1;j<=s.length();j++){
            if(wordDict.contains(s.substring(idx,j))){
                int l = res.length();
                res = res + " " + s.substring(idx,j);
                dfs(s,wordDict,res,j);
                res = res.substring(0,l);
            }
        }
        
    }
}


全部评论
这个方法好
点赞 回复 分享
发布于 2022-08-26 19:49 陕西

相关推荐

12-20 11:21
复旦大学 Java
点赞 评论 收藏
分享
苗条的伊泽瑞尔最喜欢...:同28届被压力了,电科✌就不能去卷算法吗?把Java留给我们双非卷
投递快手等公司10个岗位
点赞 评论 收藏
分享
牛至超人:把哈工大,再加大加粗,看见闪闪发光的哈工大字样,面试官直接流口水
投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
12-20 11:26
复旦大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务