组合总和 Ⅳ(LeetCode 377)

简介: 组合总和 Ⅳ(LeetCode 377)

组合总和 Ⅳ(LeetCode 377)

Description

给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s

不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。

Sample Input 1

s = "leetcode", wordDict = ["leet", "code"]

Sample Output 1

true

Sample Tips 1

返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。

Sample Input 2

s = "applepenapple", wordDict = ["apple", "pen"]

Sample Output 2

true

Sample Tips 2

返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。
注意,你可以重复使用字典中的单词。

Sample Input 3

s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]

Sample Output 3

false

Tips

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • swordDict[i] 仅有小写英文字母组成
  • wordDict 中的所有字符串 互不相同

算法思想:

看到这道题目的时候,大家应该回想到其实就是枚举字符串的所有分割情况。

分割回文串是枚举分割后的所有子串,判断是否回文。

本道是枚举分割所有字符串,判断是否在字典里出现过。

回溯法C++代码:

class Solution {
private:
    bool backtracking (const string& s, const unordered_set<string>& wordSet, int startIndex) {
        if (startIndex >= s.size()) {
            return true;
        }
        for (int i = startIndex; i < s.size(); i++) {
            string word = s.substr(startIndex, i - startIndex + 1);
            if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, i + 1)) {
                return true;
            }
        }
        return false;
    }
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
        return backtracking(s, wordSet, 0);
    }
};
  • 时间复杂度:O(2^n),因为每一个单词都有两个状态,切割和不切割
  • 空间复杂度:O(n),算法递归系统调用栈的空间

递归的过程中有很多重复计算,可以使用数组保存一下递归过程中计算的结果。

这个叫做记忆化递归,这种方法我们之前已经提过很多次了。

使用memory数组保存每次计算的以startIndex起始的计算结果,如果memory[startIndex]里已经被赋值了,直接用memory[startIndex]的结果。

class Solution {
private:
    bool backtracking (const string& s,
            const unordered_set<string>& wordSet,
            vector<bool>& memory,
            int startIndex) {
        if (startIndex >= s.size()) {
            return true;
        }
        // 如果memory[startIndex]不是初始值了,直接使用memory[startIndex]的结果
        if (!memory[startIndex]) return memory[startIndex];
        for (int i = startIndex; i < s.size(); i++) {
            string word = s.substr(startIndex, i - startIndex + 1);
            if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) {
                return true;
            }
        }
        memory[startIndex] = false; // 记录以startIndex开始的子串是不可以被拆分的
        return false;
    }
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
        vector<bool> memory(s.size(), 1); // -1 表示初始化状态
        return backtracking(s, wordSet, memory, 0);
    }
};

本文更强调采用背包问题求解。

单词就是物品,字符串s就是背包,单词能否组成字符串s,就是问物品能不能把背包装满。

拆分时可以重复使用字典中的单词,说明就是一个完全背包!

动规五部曲分析如下:

  1. 确定dp数组以及下标的含义

    dp[i] : 字符串长度为i的话,dp[i]为true,表示可以拆分为一个或多个在字典中出现的单词。

  2. 确定递推公式

    如果确定dp[j] 是true,且 [j, i] 这个区间的子串出现在字典里,那么dp[i]一定是true。(j < i )。

    所以递推公式是 if([j, i] 这个区间的子串出现在字典里 && dp[j]是true) 那么 dp[i] = true。

  3. dp数组如何初始化

    从递推公式中可以看出,dp[i] 的状态依靠 dp[j]是否为true,那么dp[0]就是递推的根基,dp[0]一定要为true,否则递推下去后面都都是false了。

    dp[0]表示如果字符串为空的话,说明出现在字典里。

    但题目中说了“给定一个非空字符串 s” 所以测试数据中不会出现i为0的情况,那么dp[0]初始为true完全就是为了推导公式。

    下标非0的dp[i]初始化为false,只要没有被覆盖说明都是不可拆分为一个或多个在字典中出现的单词。

  4. 确定遍历顺序

    题目中说是拆分为一个或多个在字典中出现的单词,所以这是完全背包。

    还要讨论两层for循环的前后顺序。

    如果求组合数就是外层for循环遍历物品,内层for遍历背包

    如果求排列数就是外层for遍历背包,内层for循环遍历物品

    本题其实我们求的是排列数,拿 s = "applepenapple", wordDict = ["apple", "pen"] 举例。

    "apple", "pen" 是物品,那么我们要求 物品的组合一定是 "apple" + "pen" + "apple" 才能组成 "applepenapple"。

    "apple" + "apple" + "pen" 或者 "pen" + "apple" + "apple" 是不可以的,那么我们就是强调物品之间顺序。

    所以说,本题一定是先遍历背包,再遍历物品。

  5. 推导dp数组

    输入s = "leetcode", wordDict = ["leet", "code"]

    dp数组状态图为:

    i:  0 1 2 3 4 5 6 7 8 
    dp: 1 0 0 0 1 0 0 0 1

    dp[s.size()]就是最终结果。

综上分析完毕,代码如下:

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
        vector<bool> dp(s.size() + 1, false);
        dp[0] = true;
        for (int i = 1; i <= s.size(); i++) {   // 遍历背包
            for (int j = 0; j < i; j++) {       // 遍历物品
                string word = s.substr(j, i - j); //substr(起始位置,截取的个数)
                if (wordSet.find(word) != wordSet.end() && dp[j]) {
                    dp[i] = true;
                }
            }
        }
        return dp[s.size()];
    }
};
  • 时间复杂度:O(n^3),因为substr返回子串的副本是O(n)的复杂度(这里的n是substring的长度)
  • 空间复杂度:O(n)

Java代码代码如下:

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        HashSet<String> set = new HashSet<>(wordDict);
        boolean[] valid = new boolean[s.length() + 1];
        valid[0] = true;

        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i && !valid[i]; j++) {
                if (set.contains(s.substring(j, i)) && valid[j]) {
                    valid[i] = true;
                }
            }
        }

        return valid[s.length()];
    }
}
目录
相关文章
|
8月前
|
人工智能 BI 索引
【Leetcode -598.范围求和Ⅱ -599.两个列表的最小索引总和】
【Leetcode -598.范围求和Ⅱ -599.两个列表的最小索引总和】
27 0
|
23天前
|
存储 算法
算法题解-组合总和3
算法题解-组合总和3
|
23天前
|
Java
leetcode-40:组合总和 II
leetcode-40:组合总和 II
24 0
|
23天前
|
Java 索引
leetcode-39:组合总和
leetcode-39:组合总和
20 0
|
23天前
|
Java
leetcode-377:组合总和 Ⅳ
leetcode-377:组合总和 Ⅳ
18 0
|
23天前
|
Java
leetcode-216:组合总和 III
leetcode-216:组合总和 III
21 0
|
8月前
代码随想录Day22 LeetCode T39 组合总和 T40 组合总和II T131 分割回文串
代码随想录Day22 LeetCode T39 组合总和 T40 组合总和II T131 分割回文串
21 0
|
12月前
|
机器学习/深度学习 算法 安全
LeetCode - #40 组合总和 II
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
|
12月前
leetcode:40.组合总和 II
给定一个数组 candidates和一个目标数 target,找出 candidates中所有可以使数字和为 target的组合。
37 0
|
12月前
leetcode:39.组合总和
给定一个无重复元素的数组 candidates和一个目标数 target,找出 candidates中所有可以使数字和为 target的组合。
47 0