算法之动态规划中

1.动态规划

1.剑指offer 10-2 青蛙跳台阶

dp[n] = dp[n-1]+dp[n-2]
dp[0] = 1  
dp[1] = 1

java:

  • 时间复杂度:O(n)
  • 空间复杂度:O(n) 可优化为O(1)
class Solution {
    public int numWays(int n) {
        if(n <= 1){
            return 1;
        }
        int[] dp = new int[n+1];
        dp[0] = 1;
        dp[1]= 1;
        for(int i = 2;i<=n;i++){
            dp[i] = dp[i-1]+dp[i-2];
            dp[i] %= 1000000007;
        }
        return dp[n];
    }
}

python3:

class Solution:
    def numWays(self, n: int) -> int:
        if n <= 1:
            return 1
        dp = [0]*(n+1)
        dp[0] = 1
        dp[1] = 1
        for i in range(2,n+1):
            dp[i] = dp[i-1] + dp[i-2]
            dp[i] %= 1000000007
        return dp[n]

2.LeetCode 62.不同路径

dp[i] [j] = dp[i-1] [j] + dp[i] [j-1]
目标:求dp[m-1][n-1]

java:

  • 时间复杂度:O(m*n)
  • 空间复杂度:O(m*n)
class Solution {
    public int uniquePaths(int m, int n) {
        //边界条件
        if(m <= 0 || n<= 0) return 0;
        //创建一个二维数组
        int[][] dp = new int[m][n];
        //初始值
        for (int i = 0; i < n; i++) {
            dp[0][i] = 1;
        }
        for (int i = 0; i < m; i++) {
            dp[i][0] = 1;
        }
        //状态方程
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[m - 1][n - 1];  
    }
}

python3:

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        #创建m*n的空二维数组
        dp=[[0 for col in range(m)] for row in range(n)]
        #初始值
        for i in range(m):
            dp[0][i]=1
        for i in range(n):
            dp[i][0]=1
        #状态方程
        for i in range(1,n):
            for j in range(1,m):
                dp[i][j]=dp[i-1][j]+dp[i][j-1]
        return dp[m-1][n-1]

3.LeetCode 696. 计数二进制子串

class Solution:
    def countBinarySubstrings(self, s: str) -> int:
        ans=0
        last=''
        j=k=0
        for i in s:
            if last==i:j+=1
            else:
                last=i
                ans+=min(j,k)
                k,j=j,1
        return ans+min(j,k)

4.解码方式

例如:226可拆解成BBF、BA、VF的组合。

f(n)=f(n-1)+f(n-2)

考虑限制条件:

# coding=utf-8
# 例如:226可拆解成BBF、BA、VF的组合。

def numDecoding(s):
    if s == "" or s[0] == '0':
        return 0
    dp = [1, 1]
    for i in range(2, len(s) + 1):
        if 10 <= int(s[i - 2:i]) <= 26:
            result = dp[i - 2]
        if s[i - 1] != '0':
            result += dp[i - 1]
        dp.append(result)
    return dp[len(s)]

# Test
print(numDecoding("110"))
result:1

5.买卖股票

问题描述:给定一个数组,表示每天的股票价格,可以进行一次交易(先买再卖),如何能得到最大利润。

# coding=utf-8
def maxProfit(prices):
    if len(prices) < 2:
        return 0
    min_price = prices[0]
    max_profit = 0
    for price in prices:
        if price < min_price:
            min_price = price
        if price - min_price > max_profit:
            max_profit = price - min_price
    return max_profit

#Test
prices = [7, 1, 5, 3, 6,4 ]
print(maxProfit(prices))
result:5

动态规划写法:

# coding=utf-8
# DP写法
def maxProfit(prices):
    if len(prices) < 2:
        return 0
    minPrice = prices[0]
    dp = [0] * len(prices)
    for i in range(len(prices)):
        dp[i] = max(dp[i - 1], prices[i] - minPrice)
        minPrice = min(minPrice, prices[i])
    return dp[-1]

# Test
prices = [7, 1, 5, 3, 6, 4]
print(maxProfit(prices))
result:5

6.买卖股票2

可以进行多次交易,再次买入的时候必须将之前的股票卖出。

# coding=utf-8
# 买卖股票2,可以进行多次交易,再次买入的时候必须将之前的股票卖出。

def maxProfit2(prices):
    max_profit = 0
    for i in range(1, len(prices)):
        if prices[i] > prices[i - 1]:
            max_profit += prices[i] - prices[i - 1]
    return max_profit

# Test
prices = [7, 1, 5, 3, 6, 4]
print(maxProfit2(prices))
result:7

写法2:

# coding=utf-8
def maxProfit2(prices):
    max_profit = 0
    for i in range(1, len(prices)):
        max_profit += max(0,prices[i]-prices[i-1])
    return max_profit

# Test
prices = [7, 1, 5, 3, 6, 4]
print(maxProfit2(prices))

7.买卖股票3

可以进行任意多次交易,但每次需要交纳k元手续费 。

  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
# coding=utf-8
def maxProfit3(prices,fee):
    cash,hold = 0, -prices[0]
    for i in range(1,len(prices)):
        cash, hold = max(cash,hold+prices[i]-fee),max(hold,cash-prices[i])
    return cash

# Test
prices = [1, 3, 2, 8, 4, 9]
fee = 2
print(maxProfit3(prices,fee))
result:8

8.买卖股票4

只能进行***两次***交易

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值