题目链接:https://leetcode.com/problems/house-robber/
答案自然是动态规划(Dynamic programming,简称DP)。
代码
func rob1(nums []int) int { lth := len(nums) if lth == 0 { return 0 } dp := make([]int, lth+1) dp[1] = nums[0] for i := 2; i < lth+1; i++ { dp[i] = int(math.Max(float64(nums[i-1] + dp[i-2]), float64(dp[i-1]))) } return dp[lth] }
变种题House Robber II
代码
func rob2(nums []int) int { lth := len(nums) if lth == 0 { return 0 } else if lth == 1 { return nums[0] } return int(math.Max(float64(rob1(nums[:lth-1])), float64(rob1(nums[1:lth])))) }
第一次做的时候,我并不是这么写的。
受到《算法导论》中矩阵链乘法的影响,我采用的是二维视角。
rob1的代码如下:
func rob1(nums []int) int { lth := len(nums) if lth == 0 { return 0 } else if lth == 1 { return nums[0] } else if lth == 2 { return int(math.Max(float64(nums[0]), float64(nums[1]))) } dp := make([][]int,lth+1) for i := 0; i <= lth; i++ { dp[i] = make([]int,lth+1) } // 长度为1的 for i := 1; i <= lth; i++ { dp[i][i] = nums[i-1] } // 长度为2的 for i := 1; i < lth; i++ { dp[i][i+1] = int(math.Max(float64(nums[i-1]),float64(nums[i]))) } // 长度>=3的 for l := 3; l <= lth;l++ { for i := 1; i <= lth+1 - l; i++ { j := i+ l -1 dp[i][j] = int(math.Max(float64(dp[i][j-1]), float64(dp[i][j-2] + nums[j-1]))) } } return dp[1][lth] }
rob2相比rob1,只有在长度为n的情况下,才需要特殊处理下
func rob2(nums []int) int { lth := len(nums) if lth == 0 { return 0 } else if lth == 1 { return nums[0] } else if lth == 2 { return int(math.Max(float64(nums[0]), float64(nums[1]))) } dp := make([][]int,lth+1) for i := 0; i <= lth; i++ { dp[i] = make([]int,lth+1) } // 长度为1的 for i := 1; i <= lth; i++ { dp[i][i] = nums[i-1] } // 长度为2的 for i := 1; i < lth; i++ { dp[i][i+1] = int(math.Max(float64(nums[i-1]),float64(nums[i]))) } // 长度>=3的 for l := 3; l < lth;l++ { for i := 1; i <= lth+1 - l; i++ { j := i+ l -1 dp[i][j] = int(math.Max(float64(dp[i][j-1]), float64(dp[i][j-2] + nums[j-1]))) } } return int(math.Max(float64(dp[1][lth-1]),float64(dp[2][lth-2] + nums[lth-1]))) }