zoukankan      html  css  js  c++  java
  • 动态规划_leetcode198拓展

    #coding=utf-8
    # 1
    # 对状态的定义 : 考虑偷取[x...n-1]范围里的房子


    class Solution1(object):
    def rob(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """

    if not nums:
    return 0


    length = len(nums)

    if length == 1:
    return nums[0]

    memo = [-1 for i in range(length)]
    memo[length-1] = nums[length-1]

    for i in range(length-2 ,-1 ,-1):
    for j in range(i,length):
    if j+2 < length:
    memo[i] = max(memo[i],nums[j] + memo[j+2])
    else:
    memo[i] = max(memo[i],nums[j])

    return memo[i]


    # 2
    # 对状态的定义: 考虑偷取[0...x]范围里的房子

    class Solution2(object):
    def rob(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """

    if not nums:
    return 0


    length = len(nums)

    if length == 1:
    return nums[0]

    memo = [-1 for i in range(length)]
    memo[0] = nums[0]

    for i in range(1,length):
    for j in range(i,-1,-1):

    if j-2 >=0:
    memo[i] = max(memo[i],nums[j] + memo[j-2])
    else:
    memo[i] = max(memo[i],nums[j])


    return memo[length-1]


    s = Solution2()
    nm = [1,2,3,1]
    print s.rob(nm)
  • 相关阅读:
    兼容性处理
    H5 IOS 虚拟键盘不回落的问题
    git 的版本控制
    vue-devtools工具的安装
    linux下安装mysql
    Python安装pip3常见问题
    linux下安装python3
    接口_注册接口
    接口_简单get接口_第一个接口
    Python学习笔记_Redis
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546524.html
Copyright © 2011-2022 走看看