dp总结

dp四要素

  1. 状态(存储小规模问题的结果)
  2. 方程(状态之间的联系,怎么通过小的状态,来算大的状态)
  3. 初始化(最极限的小状态是什么)
  4. 答案(最大的状态是什么)

LeetCode53:最大子序和

(动态规划) O(n)
f ( i ) f(i) f(i)表示以第 i个数字为结尾的最大连续子序列的 和 是多少。
初始化 f ( 0 ) = n u m s [ 0 ] f(0)=nums[0] f(0)=nums[0]
转移方程 f ( i ) = m a x ( f ( i − 1 ) + n u m s [ i ] , n u m s [ i ] ) ) f(i)=max(f(i−1)+nums[i],nums[i])) f(i)=max(f(i1)+nums[i],nums[i]))。可以理解为当前有两种决策,一种是将第 i个数字和前边的数字拼接起来;另一种是第 i 个数字单独作为一个新的子序列的开始。
最终答案为 a n s = m a x ( f ( k ) ) , 0 ≤ k < n ans=max(f(k)),0≤k<n ans=max(f(k)),0k<n

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int res;
        int n = nums.size();
        vector<int> f(n);
        f[0] = nums[0]; // init
        res = f[0];
        for (int i = 1; i < n; i++){
            f[i] = max(f[i - 1] + nums[i], nums[i]);
            res = max(res, f[i]);
        }
        return res;    
    }
    
};

word break

Given an input string and a dictionary of words, segment the input string into a space=separated dequence of dictionary words if possible. For example, if the input string is "applepie" and dictionary contains a standard set of English words, then we would return the string "apple pie" as output.

bool wordBreak(string s, unordered_set<string> &dict) {
    int begin = 0, end = 0;
    string word; 
    bool words[s.size()+1] = {0};
    words[0] = true;

    for (int i = 1; i < s.size() + 1; i++) {
        words[i] = false;
        for (end = 0; end < s.size(); end++) {
            for(begin = 0; begin <= end; begin++)
                if (words[begin] && dict.find( s.substr(begin, end-begin+1) ) 
!= dict.end()) {
                    words[end + 1] = true;
                    break;
                }
         }
    }

    return words[s.size()];
}	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

量子孤岛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值