defsimple_rob(nums): prev2, prev1 = 0, 0 for num in nums: tmp = prev1 prev1 = max(prev2+num, prev1) prev2 = tmp return prev1 returnmax(simple_rob(nums[1:]), simple_rob(nums[:-1]))
123. Best Time to Buy and Sell Stock III
1 2 3 4
Input: prices = [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
classSolution: defchange(self, amount: int, coins: List[int]) -> int: dp = [0]*(amount+1) dp[0] = 1 for c in coins: for i inrange(1, amount+1): if i >= c: dp[i] = dp[i] + dp[i-c] return dp[amount]
62. Unique Path
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defuniquePaths(self, m: int, n: int) -> int: ifnot m ornot n: return0 dp = [[1for _ inrange(m)] for _ inrange(n)] for i inrange(1,n): for j inrange(1,m): # 注意这里,i j 是两个状态,到达这个状态 有两个子情况 dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1]
377. Combination Sum IV
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defcombinationSum4(self, nums: List[int], target: int) -> int: dp = [0]*(target+1) dp[0] = 1 for i inrange(1, target+1): for num in nums: if num <= i: dp[i] += dp[i-num] return dp[target] defcombinationSum4(self, N: List[int], T: int) -> int: dp = [0] * (T + 1) dp[0] = 1 for i inrange(T): ifnot dp[i]: continue for num in N: if num + i <= T: dp[i+num] += dp[i] return dp[T]