Leetcode139单词拆分及其多种变体问题

1 声明

1.1 首先,大家常常把这道题当作了背包问题来做,因为其循环结构和背包问题刚好相反,但事实如此嘛?

背包问题通常都是组合问题,这其实是一道""面向目标值的排列问题",具体和背包问题有什么不同可以参考我下面写的这篇文章"面向目标值的排列匹配"和"面向目标值的背包组合问题"的区别和leetcode例题详解

2 原题

java 复制代码
    public boolean wordBreak(String s, List<String> wordDict) {
        int n=s.length();
        char[]cs=s.toCharArray();
        int m=wordDict.size();

        HashSet<String>set=new HashSet<>(wordDict);
        boolean[]f=new boolean[n+1];
        f[0]=true;

        for(int i=1;i<=n;i++){
            for(int j=0;j<i;j++){
                if(f[j]&&set.contains(s.substring(j,i))){
                    f[i]=true;
                    break;
                }
            }
        }
        return f[n];
    }

3 改编一:求凑成目标串的方案数,如果凑不成返回0

java 复制代码
    //求方案数,使用两个函数
    public int wordBreak3(String s, List<String> wordDict) {
        int n=s.length();
        char[]cs=s.toCharArray();
        int m=wordDict.size();

        HashSet<String>set=new HashSet<>(wordDict);
        boolean[]f=new boolean[n+1];
        f[0]=true;

        int[]f2=new int[n+1];
        f2[0]=1;

        for(int i=1;i<=n;i++){
            for(int j=0;j<i;j++){
                if(f[j]&&set.contains(s.substring(j,i))){
                    f[i]=true;
                    f2[i]+=f2[j];
                }
            }
        }
        return f2[n];
    }
    // 方案二:直接使用一个dp函数
    public int wordBreak(String s, List<String> wordDict) {
        int n=s.length();
        char[]cs=s.toCharArray();
        int m=wordDict.size();

        HashSet<String>set=new HashSet<>(wordDict);

        int[]f2=new int[n+1];

        f2[0]=1;

        for(int i=1;i<=n;i++){
            for(int j=0;j<i;j++){
                if(f2[j]>0&&set.contains(s.substring(j,i))){
                    f2[i]+=f2[j];
                }
            }
        }
        System.out.println(f2[n]);
        return true;
    }

4 Leetcode 140. 单词拆分 II

相关推荐
pystraf21 分钟前
UOJ 228 基础数据结构练习题 Solution
数据结构·c++·算法·线段树
祁同伟.40 分钟前
【数据结构 · 初阶】- 堆的实现
c语言·数据结构
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
永远在Debug的小殿下2 小时前
查找函数【C++】
数据结构·算法
我想进大厂3 小时前
图论---染色法(判断是否为二分图)
数据结构·c++·算法·深度优先·图论
Yhame.3 小时前
【使用层次序列构建二叉树(数据结构C)】
c语言·开发语言·数据结构
雾月554 小时前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
Pasregret4 小时前
访问者模式:分离数据结构与操作的设计模式
数据结构·设计模式·访问者模式
OpenC++4 小时前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft