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

相关推荐
全栈凯哥33 分钟前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥36 分钟前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu40 分钟前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
lyh13441 小时前
【SpringBoot自动化部署方法】
数据结构
蒟蒻小袁2 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
MSTcheng.2 小时前
【数据结构】顺序表和链表详解(下)
数据结构·链表
慢半拍iii3 小时前
数据结构——F/图
c语言·开发语言·数据结构·c++
GalaxyPokemon3 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
iceslime3 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
witton5 小时前
美化显示LLDB调试的数据结构
数据结构·python·lldb·美化·debugger·mupdf·pretty printer