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

相关推荐
老鼠只爱大米34 分钟前
LeetCode经典算法面试题 #78:子集(回溯法、迭代法、动态规划等多种实现方案详细解析)
算法·leetcode·动态规划·回溯·位运算·子集
执着25938 分钟前
力扣hot100 - 199、二叉树的右视图
数据结构·算法·leetcode
cpp_25011 小时前
P8448 [LSOT-1] 暴龙的土豆
数据结构·c++·算法·题解·洛谷
YGGP1 小时前
【Golang】LeetCode 49. 字母异位词分组
leetcode
lcj25111 小时前
深入理解指针(4):qsort 函数 & 通过冒泡排序实现
c语言·数据结构·算法
唐梓航-求职中1 小时前
编程大师-技术-算法-leetcode-1472. 设计浏览器历史记录
算法·leetcode
YGGP1 小时前
【Golang】LeetCode 1. 两数之和
leetcode
唐梓航-求职中1 小时前
编程大师-技术-算法-leetcode-355. 设计推特
算法·leetcode·面试
仰泳的熊猫1 小时前
题目1453:蓝桥杯历届试题-翻硬币
数据结构·c++·算法·蓝桥杯
唐梓航-求职中1 小时前
技术-算法-leetcode-1606. 找到处理最多请求的服务器(易懂版)
服务器·算法·leetcode