代码随想录算法训练营第四十天|leetcode139题

一、leetcode第139题

本题是完全背包问题,由于可以重复使用,因此需要先遍历背包再遍历物品,dp[i]的含义是在长度为i处能否从数组中找到元素组成。

具体代码如下:

cpp 复制代码
class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
    vector<bool>dp(s.length()+1,false);
    unordered_set<string>wordset(wordDict.begin(),wordDict.end());
    dp[0]=true;
    for(int i=1;i<=s.length();i++)
    {
        for(int j=0;j<i;j++)
        {
            string word=s.substr(j,i-j);
            if(wordset.find(word)!=wordset.end()&&dp[j]==true)
            {
                dp[i]=true;
            }
        }
    }
    return dp[s.length()];
    }
};
相关推荐
penguin_bark2 分钟前
69. x 的平方根
算法
这可就有点麻烦了12 分钟前
强化学习笔记之【TD3算法】
linux·笔记·算法·机器学习
苏宸啊18 分钟前
顺序表及其代码实现
数据结构·算法
lin zaixi()21 分钟前
贪心思想之——最大子段和问题
数据结构·算法
FindYou.22 分钟前
C - Separated Lunch
算法·深度优先
夜雨翦春韭28 分钟前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
Kent_J_Truman39 分钟前
【平方差 / C】
算法
一直学习永不止步40 分钟前
LeetCode题练习与总结:H 指数--274
java·数据结构·算法·leetcode·数组·排序·计数排序
Amor风信子1 小时前
华为OD机试真题---跳房子II
java·数据结构·算法
戊子仲秋1 小时前
【LeetCode】每日一题 2024_10_2 准时到达的列车最小时速(二分答案)
算法·leetcode·职场和发展