Bootstrap

代码随想录算法训练营第四十六天—动态规划008

第一题、单词拆分 力扣题目链接

谨记:

求组合数是先遍历物品,后遍历背包;

求排列数是先遍历背包,后遍历物品。

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);
                if(wordSet.find(word) != wordSet.end() && dp[j]){
                    dp[i] = true;
                }
            }
        }
        return dp[s.size()];
    }
};

动态规划之背包问题总结:

 

 

;