[leetcode]初级算法——动态规划

爬楼梯

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Code(By myself):

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        # way = 1
        # if n <= 3:
        #     return n
        # else:
        #     way = (self.climbStairs(n - 1) + self.climbStairs(n - 2))
        #     return way
        a = 1
        b = 1
        for i in range(n):
            a, b = b, a + b
        return a
Code(others):
class Solution(object):
    def climbStairs(self, n):
        if n == 1:
            return 1
        res = [0 for i in xrange(n)]
        res[0], res[1] = 1, 2
        for i in xrange(2, n):
            res[i] = res[i-1] + res[i-2]
        return res[-1]

总结:

Fibonacci数列

买卖股票的最佳时机

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Code(By myself):

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        # profit = 0
        # for i in range(len(prices)):
        #     j = i + 1
        #     k = prices[i]
        #     while j < len(prices):
        #         if prices[j] > k:
        #             k = prices[j]
        #         j += 1
        #     if k - prices[i] > profit:
        #         profit = k - prices[i]
        # return profit
        change = []
        profit = 0
        temp = 0
        for i in range(len(prices)-1):
            change.append(prices[i + 1] - prices[i])
        for i in change:
            if i + temp > 0:
                temp += i
            else:
                temp = 0
            profit = max(profit, temp)
        return profit
Code(others):
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)==0:
            return 0
        min_ = sys.maxint
        cur_max = 0
        
        for price in prices:
            if price >min_:
                cur_max = max(cur_max,price-min_)
            else:
                min_=price
        return cur_max
                

最大子序和

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Code(By myself):

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max_ = -float('inf')
        temp = -float('inf')
        add_max = -float('inf')
        for i in nums:
            if max_ < i:
                max_ = i
            temp = temp + i
            temp = max(temp, i)
            add_max = max(temp, max_, add_max)
        return add_max
Code(others):
class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        summ = 0
        max_sum = nums[0]
        for i in nums:
            summ+=i
            if max_sum < summ:
                max_sum = summ
            if summ < 0:
                summ = 0
        return max_sum

打家劫舍

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Code(By myself):

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # if len(nums) == 0:
        #     return 0
        # elif len(nums) == 1:
        #     return nums[0]
        # elif len(nums) == 2:
        #     return max(nums[0], nums[1])
        # elif len(nums) == 3:
        #     return max(nums[0] + nums[2], nums[1])
        # first = nums[0]
        # second = nums[1]
        # third = nums[2] + first
        # for i in range(3, len(nums)):
        #     max_ = max(first + nums[i], second + nums[i], third)
        #     first = second
        #     second = third
        #     third = max_
        # return max_
        last = 0 
        now = 0
        for i in nums: last, now = now, max(last + i, now)
        return now

总结:

递推关系:g[i] = max(g[i-1],g[i-2]+nums[i])


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值