Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

打家劫舍 II #134

Open
yankewei opened this issue Apr 15, 2021 · 1 comment
Open

打家劫舍 II #134

yankewei opened this issue Apr 15, 2021 · 1 comment
Labels
中等 题目难度为中等 动态规划 题目包含动态规划解法

Comments

@yankewei
Copy link
Owner

你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。

给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,能够偷窃到的最高金额。

示例 1:

输入:nums = [2,3,2]
输出:3
解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。

示例 2:

输入:nums = [1,2,3,1]
输出:4
解释:你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
     偷窃到的最高金额 = 1 + 3 = 4 。

示例 3:

输入:nums = [0]
输出:0

提示:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 中等 题目难度为中等 动态规划 题目包含动态规划解法 labels Apr 15, 2021
@yankewei
Copy link
Owner Author

动态规划

这个题和 #33 类似,只不过这里的房屋首尾相连了。
其实可以这么分析,如果我偷第一家,那么最后一家必定不能偷,也就是说数组的最后一项其实是没用的。或者最后一家要偷,那么第一家肯定是不能偷的,所以数组的第一项是没有用的。

func rob(nums []int) int {
    if len(nums) == 1 {
        return nums[0]
    }
    return max(_rob(nums[1:]), _rob(nums[:len(nums)-1]))
}

func _rob(nums []int) int {
    d := [2]int{0, 0}
    for _,value := range nums {
	tmp := d[0]
	d[0] = d[1]
	d[1] = max(tmp + value, d[1])
    }
    return d[1]
}

func max(a int, b int) int {
    if a > b {
        return a
    }
    return b
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 动态规划 题目包含动态规划解法
Projects
None yet
Development

No branches or pull requests

1 participant