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

相关推荐
Navigator_Z3 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
jiushiapwojdap5 小时前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
纽扣6676 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
xvhao20138 小时前
单源、多源最短路
数据结构·c++·算法·深度优先·动态规划·图论·图搜索算法
We་ct9 小时前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划
m0_6294947310 小时前
LeetCode 热题 100-----17.缺失的第一个正数
数据结构·算法·leetcode
Tisfy10 小时前
LeetCode 0796.旋转字符串:暴力模拟
算法·leetcode·题解·模拟·字符串匹配
hnjzsyjyj11 小时前
洛谷 P1443:马的遍历 ← BFS
数据结构·bfs
小雅痞11 小时前
[Java][Leetcode middle] 209. 长度最小的子数组
java·算法·leetcode
做时间的朋友。11 小时前
精准核酸检测
java·数据结构·算法