LeetCode 之动态规划

【2022KaliLinux】openvas/gvm 没有scan configs 或者是 scan config error “XXXXXXXXXXX” gvm/openvas的configuration的scan config为空 阅读详情

1. Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

一维动态规划,从左到右扫描

bool canJump1(int A[], int n){
    int maxCover = 0;
    for(int start = 0; start<=maxCover && start<n;start++){
        if(A[start]+start > maxCover)
            maxCover = A[start]+start;
        if(maxCover >=n-1)
            return true;
    }
    return false;
}

方法二:

直接实现,len记录当前Jump距离,大于等于n-1时返回true

bool canJump(int A[], int n) {
    int len = 0;
    int *p = A;
    while(len<n){
        int dis = *p;
        if(dis == 0 && len < n-1)
            return false;
        len+=dis;
        if(len == n-1 || (len== n && dis == len))
            return true;
        p += dis;
    }
    return true;

}

2 Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?


Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

一维DP。 Step[i][j] = Step[i-1][j] + Step[i][j-1];

int uniquePaths(int m, int n) {
    vector <int> maxpath(n,0);
    maxpath[0] = 1;
    for(int i=0; i<m;i++){
        for(int j=1; j<n;j++){
            maxpath[j] = maxpath[j-1]+maxpath[j];
        }
    }
    return maxpath[n-1];
}


3.Unique Paths II

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.

和Unique Path一样的转移方程:
Step[i][j] = Step[i-1][j] + Step[i][j-1] if Array[i][j] ==0
or = 0 if Array[i][j] =1


int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
    int m = obstacleGrid.size();
    if(m==0) return 0;
    int n = obstacleGrid[0].size();
    if(obstacleGrid[0][0] == 1) return 0;
    vector<int> maxpath(n,0);
    maxpath[0] = 1;
    for(int i=0; i< m; i++){
        for(int j=0;j<n;j++){
            if(obstacleGrid[i][j] == 1)
                maxpath[j] = 0;
            else if(j>0)
                maxpath[j] = maxpath[j]+maxpath[j-1];
        }
    }
    return maxpath[n-1];
}

4. Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

利用动态规划的思路。dp[i][j]表示word1的前i个字母与word2的前j个字母的编辑距离。
1)若word1[i+1]==word2[j+1] dp[i+1][j+1] = dp[i][j];否则,dp[i+1][j+1] = dp[i][j] + 1。(利用替换原则)
2)dp[i+1][j+1]还可以取dp[i][j+1]与dp[i+1][j]中的较小值。(利用删除添加原则)

总结的递推公式就是:

dp[j][i] = min(distance[j][i - 1] + insert, distance[j - 1][i] + delete, distance[j - 1][i - 1] + replace);

其中replace需要判断一下
实际dp[i+1][j+1]应当取上述两种情况的较小值。

int minDistance(string word1, string word2) {
    int s1 = word1.size();
    int s2 = word2.size();
    if(s1 == 0)
        return s2;
    if(s2 == 0)
        return s1;
    vector<int> *dp = new vector<int>[s2+1];
    for(int i=0;i<=s1;i++)
        dp[0].push_back(i);
    for(int i=0;i<=s2;i++)
        dp[i].push_back(i);
    for(int i=1;i<=s2;i++){
        for(int j=1;j<=s1;j++){
            int n1 = word2[i-1]!=word1[j-1]?(dp[i-1][j-1]+1):dp[i-1][j-1];
            int n2 = dp[i-1][j]<dp[i][j-1]?(dp[i-1][j]+1):(dp[i][j-1]+1);
            dp[i].push_back(n1<n2? n1:n2);
        }
    }
    return dp[s2][s1];
}

5.Best Time to Buy and Sell Stock

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

从左到右扫面,记录当前最低股票值,同时比较股票差值,并记录

int maxProfit(vector<int> &prices) {
    int max=0, minV = INT_MAX;
    int diff;
    for(int i=0; i<prices.size();i++){
        if(prices[i]<minV) minV = prices[i];
        diff = prices[i]-minV;
        if(diff > max)
            max = diff;
    }
    return max;
}

6.Best Time to Buy and Sell Stock II

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

从左到右扫面,记录所有差值为正的数据,之和为最大盈利

int maxProfit2(vector<int> &prices){
    int sum = 0;
    for(int i=1;i<prices.size();i++){
        if(prices[i]-prices[i-1] > 0)
            sum+= prices[i]-prices[i-1];
    }
    return sum;
}

7. Best Time to Buy and Sell stock III

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

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

MaxPro[0,n] = max(MaxPro[0,i]+MaxPro[i+1,n]);

最多只能交易两次。

两种情况,

1.从左到右只有一个股票上升的区间

2. 从左到右有多个股票上升区间,MaxPro[0,n] = max(MaxPro[0,i]+MaxPro[i+1,n]);

两个数组,一个记录从左到右扫描的每个位置的盈利值,一个记录从右到左扫描的每个位置的盈利值。

最后通过取maxFromLeft[i] maxFromRight[i+1]实现MaxPro[0,n] = max(MaxPro[0,i]+MaxPro[i+1,n]);

int maxProfit(vector<int> &prices){
    if(prices.size()<=1) return 0;
    if(prices.size()==2) return prices[1]>prices[0]?prices[1]-prices[0]:0;
    vector<int> maxFromLeft(prices.size(),0);
    vector<int> maxFromRight(prices.size(),0);
    int minL = INT_MAX, max=INT_MIN, diff;
    for(int i=0;i<prices.size();i++){
        if(prices[i]<minL) minL = prices[i];
        diff = prices[i]- minL;
        if(diff >max)
            max = diff;
        maxFromLeft[i] = max;
    }
    int maxR = INT_MIN;
    max = INT_MIN;
    for(int i=prices.size()-1;i>=0;i--){
        if(prices[i]>maxR) maxR = prices[i];
        diff = maxR - prices[i];
        if(diff > max)
            max = diff;
        maxFromRight[i] = max;
    }
    max = INT_MIN;
    for(int i=0;i<prices.size()-1;i++){
        int diff = maxFromLeft[i]+maxFromRight[i+1];
        if(diff > max) max = diff;
    }
    if(max < maxFromRight[0])
        max = maxFromRight[0];
    return max;

}


8. Restore IP address

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)


This problem can be viewed as a DP problem. There needed 3 dots to divide the string, and make sure the IP address is valid:  less than or equal to 255, greater or equal to 0, and note that, "0X" or "00X" is not valid.
For the DP, the length of each part is from 1 to 3. We use a vector<string> to store each part, and cut the string every time. Details see the code.

/*
s -- string, input
start -- startindex, start from which index in s
step -- step current step index, start from 0, valid value1-4,4 means the end
ip -- intermediate, split result in current spliting process
result -- save all possible ip address
*/
void dfsIp(string s, size_t start, size_t step, string ip,
           vector<string> &result){
    if(start == s.size() && step == 4){//find a possible result
        ip.resize(ip.size()-1);
        result.push_back(ip);
        return;
    }
    //since each part of IP address is in 0..255,the leagth of each
    // part is less than 3 and more than 0
    if(s.size()-start > (4-step)*3) return;
    if(s.size()-start < (4-step)) return;

    int num=0;
    for(size_t i=start;i<start+3;i++){
        num = num*10 + (s[i]-'0');
        if(num<=255){
            ip+=s[i];
            dfsIp(s,i+1,step+1,ip+'.',result);
        }
        if(num == 0) break;
    }
}
vector<string> restoreIpAddresses(string s) {
    vector<string> result;
    string ip; // save temporaty result in processing
    dfsIp(s,0,0,ip,result);
    return result;
}

9.Climbing a stair

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?

DP. The transition function should be:
 f(n) = f(n-1) + f(n-2)  n>2;
     or = 1   n=1
    or  = 2   n=2

int climbStairs(int n) {
        if(n==0) return 0;
    if(n==1) return 1;
    if(n==2) return 2;
    int fn=0, fn_1 = 1,fn_2=2;
    for(int i=3;i<=n;i++){
        fn = fn_2+fn_1;
        fn_1 = fn_2;
        fn_2 = fn;
    }
    return fn;
    }



10. Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

Similar as " [LeetCode] Climbing Stairs". DP. Just add some logic to compare character.

Transformation function as:
Count[i] = Count[i-1]  if S[i-1] is a valid char
       or   = Count[i-1]+ Count[i-2]  if S[i-1] and S[i-2] together is still a valid char.


int check(char one){
    return (one != '0') ? 1:0;
}
int check(char one, char two){
    return (one =='1' || (one=='2'&& two<='6'))?1:0;
}
int numDecodings(string s) {
    if(s.empty() || s[0]=='0') return 0;
    if(s.size()==1) return check(s[0]);
    int fn=0, fn_1 = 0,fn_2 = 1;
    fn_1 = (check(s[0])*check(s[1]))+check(s[0],s[1]);
    for(int i=2;i<s.size();i++){
        if(check(s[i])) fn+=fn_1;
        if(check(s[i-1],s[i])) fn+=fn_2;
        if(fn == 0)
            return 0;
        fn_2 = fn_1;
        fn_1 = fn;
        fn = 0;
    }
    return fn_1;
}


NHANES数据库实战:数据合并与加权分析技巧 本文详细解析了NHANES数据库实战中的核心技巧,重点阐述了数据合并与加权分析的正确方法。通过两个具体案例,手把手指导如何从数据下载、合并、权重计算到使用R语言survey包进行加权统计分析,避免因忽略复杂抽样设计而导致的研究偏倚,确保分析结果的准确性与可发表性。 阅读详情

相关推荐

如何设计一款四轮智能小车

此部分共分为五个小节,通过这个 Part 的学习,我们将了解机器人的概念和组成,对机器人的整体设计有一个明确的思路,然后通过机械结构、驱动系统、传感系统、控制系统四大组成部分,展开介绍设计一款智能小车的基本思路。通过这一讲课程,我们希望大家脑海中能够对智能小车有一个明确的认识和开发思路,未来我们再逐个击破,把它一点一点做出来。从控制的角度来讲,机器人可以划分为图中四大组成部分,分别是:传感系统、执行机构、驱动系统和控制系统。

qq_45488834的博客 4434

输入一个字符串,删除其中的指定字符,形成一个新的字符串:例如,字符串中内为:*****A*BC*DEF*G***,删除后字符为ABCDEFG

#include<stdio.h> void main(){ char s1[100],s2[100]; int i,j=0; gets(s1); for(i=0;s1[i]!='\0';i++){ if(s1[i]>='A'&&s1[i]<='G'){ s2[j]=s1[i]; j++; } } printf("%s",s2); }

weixin_56797865的博客 1264

Open FPV VTX与Betaflight的MSP协议配置详解:从硬件连接到OSD显示

本文详细解析了如何通过MSP协议将Open FPV VTX与Betaflight飞控进行深度集成,实现飞行数据在OSD上的稳定显示。内容涵盖从硬件连接、Betaflight端口MSP服务启用,到VTX侧配置与OSD元素布局调校的全流程,并提供了常见问题的排查思路,帮助FPV玩家构建可靠的数据叠加系统。

weixin_29201933的博客 461

LeetCode第45题:Jump Game II(C++详解)

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to r...

WangHuanToBeBest 427

指纹浏览器降维打击(下):Cloudflare Turnstile 与 hCaptcha 的底层交互逻辑

本文将深度拆解:Turnstile 与 hCaptcha 的 Iframe 沙箱通信机制,动态混淆 JS 与 PoW(工作量证明)的物理破解法则,以及如何通过 C++ 底层事件合成与环境基因强绑定,实现验证码的“无感过验”。

数据知道的博客 435

C#上位机性能优化全攻略:彻底解决界面卡顿+多线程死锁+PLC数据延迟,产线实测稳定运行2年

一开始我们用的是网上找的零散优化代码,根本满足不了要求,后来花了2个月的时间,把之前27条产线的代码整理、重构、优化,做了一套这套方案上线后,连续稳定运行2年零3个月:界面响应时间稳定在50ms以内,多线程死锁率持续为0,PLC数据延迟稳定在150ms以内,系统可用率≥99.99%,帮客户一年省下了超过480万的停线损失、罚款损失和人工成本,客户第二年就把剩下的22条产线也全部交给我们做了,还介绍了3家同行。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 301

Leetcode Jump Game

Problem: Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position.

mumenwo的专栏 531

ST03N 里看不到 SE38 / SA38?别急,这不是没记录,而是被换了名字

摘要:SAP系统中SE38/SA38事务码在ST03N统计中可能"隐身",因其对话步骤被归集到对应的程序名(如SE38→RSABAPPROGRAM)。ST03N侧重工作负载聚合统计,而STAD提供短期明细记录。正确排查方法是:在ST03N中搜索程序名而非事务码,再通过STAD验证具体使用情况。这一现象在权限整改和审计中易造成误判,建议将程序名纳入常规监控,并区分ST03N(趋势分析)与STAD(事实校验)的不同用途。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 969

保研面试 算法题_面试高频算法题:动态规划和递归例题讲解

Hello, 刚刚结束完一天的工作,忙着把算法题写完.那么今天继续讲解算法题第55题, 也是一道经典的面试题目,那我们来一起看一看吧.Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array repr...

weixin_36474795的博客 312

C++ 中的联编(Linking)

联编(Linking)是指将多个对象文件(Object Files)和库文件(Libraries)结合起来,最终生成可执行文件的过程。它发生在编译后、程序执行前。联编的目的是将程序中的各个部分(包括函数、变量等)链接在一起,确保程序能够正确执行。在链接阶段,如果链接器无法找到某个符号(如函数或变量的定义),它会报出“未定义的引用”错误。函数或变量在源代码中声明,但没有定义。编译时没有包含正确的库文件或目标文件。解决方法确保每个声明的符号都有定义。确保在链接时包含了正确的库或目标文件。

m0_62599305的博客 997

YOLOv11改进 | 检测头篇 | 利用动态蛇形卷积DySnakeConv改进yolov11分割检测头(全网独家首发,Segment)

本文给大家带来的最新改进机制是一种我进行优化的专用于分割的检测头,在分割的过程中,最困难的无非就是边缘的检测,动态蛇形卷积(Dynamic Snake Convolution)通过自适应地聚焦于细长和迂回的局部结构,准确地捕捉管状结构的特征。这种卷积方法的核心思想是,通过动态形状的卷积核来增强感知能力,针对管状结构的特征提取进行优化,所以将这个卷积针对于YOLOv11的分割头进行融合是非常合适的,当然本文的检测头也支持用于目标检测,但是我将其设计出来是主要为了分割的读者使用的。

Snu77的博客 3448

[Codility]Lesson4

TEST1 A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river. You are given

weixin_55703970的博客 469

华为OD机试双机位C卷 - 高矮个子排队 (C++/Py/Java/Js/Go/C)

华为OD机试双机位C卷 高矮个子排队,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解。华为OD机试 - 高矮个子排队。

qq_45776114的博客 2168

力扣动态规划

力扣动态规划1. 斐波那契数列70. 爬楼梯1要求2 思路198. 打家劫舍1要求2.思路2131 要求2.思路矩阵路径64. 最小路径和1 要求2.思路62. 不同路径1要求 1. 斐波那契数列 70. 爬楼梯 1要求 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数。 示例 1: 输入: 2 输...

dayday学习的博客 1831

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

力扣(leetcode)题目总结——动态规划篇

本系列文章初衷是为了按类别整理出力扣(leetcode)最经典题目,一共100多道题,每道题都给出了非常详细的解题思路、算法步骤、代码实现。因为力扣题目顺序是随机的,并没有按照算法分类,导致同一类型的算法强化训练不够。所以本系列文章就是来帮你完成算法分类,针对每种算法做强化训练,保证让你以后遇到题目直接秒杀。本篇文章主要是针对动态规划相关的算法题,一次性帮你搞定所有动态规划题!

weixin_46571171的博客 3079

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

力扣 —— 动态规划(基础题目)

【代码】随想录 —— 动态规划。

m0_73557953的博客 234

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

【LeetCode】(动态规划ி)力扣之最

【LeetCode】(动态规划ி)力扣之最 文章目录【LeetCode】(动态规划ி)力扣之最最长和谐子序列★最长连续递增序列★最长递增子序列(LIS)★★最长公共子序列(LCS)★★最长回文子序列★★最长定差子序列★★最长重复子数组★★最长湍流子数组★★ 最长和谐子序列★ LeetCode 594. 最长和谐子序列 【题目】和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。 现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。 【示例】 输入: [1,3,2,2,

像写诗一样优雅地写代码~ 1万+

算法|LeetCode(力扣)经典题:动态规划

LeetCode经典(数据结构与算法)题刷题指南:动态规划篇

峰峰的博客 2959

力扣hot100二刷——动态规划

第二次刷题不在idea写代码,而是直接在leetcode网站上写,“逼”自己掌握常用的函数。

weixin_49426115的博客 976

2023-04-26 力扣LeetCode上的DP动态规划问题分类汇总

所有线性递推关系都可以用矩阵快速幂做,可以O(logN),最典型是斐波那契数列。计数型DP都可以以组合数学的方法写出组合数,然后dp求组合数。本质是 dfs + 记忆化,用在状态的转移方向不确定的情况。策梅洛定理,SG 定理,minimax。

lsgwr的博客 801

力扣labuladong一刷day59天动态规划

递推公式为dp[j] = min(dp[j-coins[i]] + 1, dp[j]),求最少物品数量,有两种选择,要么是放入当前物品,要么是不放入当前物品。思路:这是非常典型的一道题,下面是优化过的代码,a,b就是dp数组,因为每计算一个值,需要前两个值,这个a,b就是用来记录前两个值,避免重复计算,递推公式便是f(n) = f(n-1)+f(n-2)。题目链接:https://leetcode.cn/problems/fibonacci-number/description/

qq_43511039的博客 610

最详细,最简单的力扣(leetcode)hot 100 动态规划(上)篇讲解

本期带来的是力扣 hot 100里面关于动态规划内容。希望本篇博客能帮助到正在学历力扣 hot 100的你

yyyCode的博客 1115

最详细,最简单的力扣(leetcode)hot 100 动态规划(下)篇讲解

最详细的关于力扣(leetcode)hot 100的动态规划的下半部分的内容。保证看了的朋友都能学会

yyyCode的博客 1880

最详细,最简单的力扣(leetcode)hot 100 多维动态规划篇讲解

最详细的多维动态规划问题的解决方法。保证看了的都能够学会

yyyCode的博客 2399

[LeetCode 困难 动态规划] 移除盒子

题目描述 给出一些不同颜色的盒子,盒子的颜色由数字表示,即不同的数字表示不同的颜色。 你将经过若干轮操作去去掉盒子,直到所有的盒子都去掉为止。每一轮你可以移除具有相同颜色的连续 k 个盒子(k >= 1),这样一轮之后你将得到 k*k 个积分。 当你将所有盒子都去掉之后,求你能获得的最大积分和。 示例: 输入:boxes = [1,3,2,2,2,3,4,3,1] 输出:23 解释: [1, 3, 2, 2, 2, 3, 4, 3, 1] ----> [1, 3, 3, 4, 3, 1] (33

weixin_50088096的博客 266

Leetcode力扣常考高频题-动态规划

考察频率由两个部分组成 Leetcode100题 面试考察频率(https://codetop.cc/#/home)表格中默认超过30次即为高频题 题号 难度 题目描述 解法 考察频率 53 简单 最大子序列和 动归 -> 约化成<0则舍 Leetcode100+高频 6

luy0710的博客 428
上一篇: LeetCode 之堆栈 stack
下一篇: LeetCode 之哈希表 map
Mavs
博客等级 码龄17年 166粉丝 296原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值