class Solution(object): def rob(self, nums): length = len(nums) memo = [0 for index in range(length)] if length == 0: return 0 elif length == 1: return nums[0] elif length == 2: return max(nums[0], nums[1]) memo[0] = nums[0] memo[1] = nums[1] memo[2] = memo[0] + nums[2] for x in range(3, length): memo[x] = max(memo[x - 2], memo[x - 3]) + nums[x] return max(memo[length - 1], memo[length - 2])
代码是这样的,同样是动态规划,状态的定义不同为何会影响算法的时间复杂度,还是说定义为(i, n-1]的状态还有更好的写法。谢谢老师