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

相关推荐
余额瞒着我当琳6 小时前
红黑树的实现--红黑树的概念、规则、效率、结构、旋转、查找、验证
数据结构·c++·算法
程序员南飞6 小时前
win系统安装minio
java·数据结构·算法
longlongzihan7 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
苦瓜打怪兽7 小时前
leetcode 热题100(11. 盛最多水的容器)
python·算法·leetcode
w_zero_one8 小时前
链表(4)
java·数据结构·算法
白山编程大哥10 小时前
C语言篇:语法进阶
c语言·数据结构·算法
Logic10111 小时前
C语言/数据结构动态规划题解:爬楼梯(含坏台阶)——避开障碍物的路径计数
c语言·数据结构·动态规划·时间复杂度·空间复杂度·算法题·爬楼梯
All for pursuit.12 小时前
【回溯-6】79.单词搜索
数据结构·c++·算法·leetcode
Navigator_Z12 小时前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode
Benny_Tang12 小时前
AT_arc180_d [ARC180D] Division into 3 题解
数据结构·c++·算法