LeetCode刷题流程:动态规划-15.139. 单词拆分(可打印状态转移过程完整程序)

Carl大佬的详细解释和答案

139.单词拆分题目

直接动态规划,之前没有考虑到可能当前位置已经满足,提交之后发现错误。经过打印发现问题,由于当前位置更新可分true和不可分false之后,后来继续分割时可能又不满足了,所以在更新dp[n]的时候应该考虑dp[n]是否为true,因此需要或运算。

ac总消耗:
4ms 7.3MB

本人解答:

#include<string>
#include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        vector<bool>dp(s.length() + 1, false);
        dp[0] = true;
        for (int n = 0; n <= s.length(); ++n)
        {
            for (int m = 0; m < wordDict.size(); ++m)
            {
                //if (n >= wordDict[m].length())
                //{
                    //cout << "berfor is: " << dp[n - wordDict[m].length()] << endl;
                    //cout<<"substr: "<<s.substr(n - wordDict[m].length(), wordDict[m].length())<<endl;
                    //cout << "now str: " << wordDict[m] << endl;
                //}
                if (n >= wordDict[m].length() && (s.substr(n - wordDict[m].length(), wordDict[m].length()) == wordDict[m]))
                {
                    dp[n] =dp[n]||dp[n - wordDict[m].length()]&& s.substr(n - wordDict[m].length(), wordDict[m].length()) == wordDict[m];
                }
            }
            //for (auto d : dp)cout << d << " ";
            //cout << endl;
        }
        return dp[s.length()];
    }
};
int main()
{
    Solution kill;
    string s = "dogs";
    vector<string>wordDict{ "dog","s","gs" };
    if (kill.wordBreak(s, wordDict))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值