特工的特

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

动态规划在很多情况下可以降低代码的空间时间复杂度。

判断一道问题能否应用动态规划,需要关注问题是否具有最优子结构,当前规模的问题的解在之前问题的解里面,还要注意的是要满足无后效性的原则。随后就是寻找递归方程。通常使用一维数组,二维数组,甚至三维数组来存储不同规模问题的解,一些情况下也可以使用 O(1) 的空间来存储解,具体要视递归方程而定。以leetcode几个问题为例。

leetcode 53. Maximum Subarray

  Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

  For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
  the contiguous subarray [4,-1,2,1] has the largest sum = 6.

  这道题目里,对包括该数字的最大sum,dp[i] = max(dp[i-1],nums[i]).res = max(res,dp[i]). 遍历一遍就能找到最大的sum

  

if nums==[]:
            return 0
        res = nums[0]
        pre = nums[0]
        for i in xrange(1,len(nums)):
            pre = max(nums[i],pre+nums[i])
            res = max(res,pre)
        return res

  这里并不需要存储所有的dp,只需要存储 pre 即可。

 

leetcode 72. Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

  这道题考虑将长度为 i 的字符串转化为长度为 j 的字符串需要最少步骤,这里如果两者最后的字符相等,只需要把 i-1 转化为 j-1 即 dp[i][j] = dp[i-1][j-1] 。 如果不相等。考虑三种操作可知 dp[i][j] = min(dp[i-1][j-1],dp[i][j],dp[i-1][j])+1.

  代码就不贴了。

 

 

  

posted on 2017-01-01 19:21  特工的特  阅读(200)  评论(0编辑  收藏  举报