基础贪心算法集合1(更新到20加油站)

贪心算法:从直觉到工程实践,C++实现与场景剖析 贪心算法是一种在每一步选择中都采取当前状态下最优决策的算法思想,其核心原理在于局部最优选择与问题的最优子结构性质。这种策略在满足特定条件时,能以较低的时间复杂度(如O(n log n)或O(n))获得全局最优解,在工程实践中具有重要价值。它广泛应用于区间调度、数据压缩(如哈夫曼编码)、资源分配等场景,例如通过优先队列高效合并节点,或利用排序快速选择结束最早的会议。然而,贪心算法并非万能,在0-1背包等问题中可能失效,需结合动态规划等其他方法。理解其适用条件与证明方法,是将其转化为可靠C++代码的关键。 阅读详情

目录

2.柠檬水找零

3.将数组和减半的最小次数

4.最大数

5.摆动序列

6.最长的递增子序列

7递增的三元子序列

8.最长连续递增序列 

9.买卖股票的最佳时机

10.买股票的最佳时机2

11.k次取反后的最大化数组和

12.按身高排序

13.优势洗牌

14.最长回文串 

15.增减字符串匹配

16.分发饼干

17.最优除法

18.跳跃游戏

 19.跳跃游戏2

20.加油站


2.柠檬水找零

class Solution {
public:
    bool lemonadeChange(vector<int>& bills) 
    {
        int five = 0;
        int ten = 0;
        for(auto ch : bills)
        {
            if(ch == 5)five++;
            else if(ch == 10)
            {
                if(five < 1)return false;
                five--;
                ten++;
            }
            else
            {
                if(five>=1 && ten >=1)//这里是贪心的点,如果有十元,优先把十元用掉,因为五元的                                                                                            
                                      //用处更大,贪五元
                {
                    five--;
                    ten--;
                }
                else if(five >= 3)
                {
                    five -= 3;
                }
                else return false;
            }
        }
        return true;
    }
};

3.将数组和减半的最小次数

class Solution {
public:
    int halveArray(vector<int>& nums) 
    {
        priority_queue<double> heap;//使用一个大根堆
        double sum = 0;
        int count = 0;
        for(auto ch : nums)
        {
            sum += ch;
            heap.push(ch);
        }
        sum /= 2.0;
        while(sum > 0)
        {
            double tmp =  heap.top()/2;
            sum -= tmp;//每次把最大数的一半减掉,贪心的点在于找最大数
            heap.pop();
            heap.push(tmp);
           count ++;

        }
        return count;
    }
};

4.最大数

class Solution {
public:
    string largestNumber(vector<int>& nums) 
    {
        vector<string>str;
        for(auto ch: nums)
        {
            str.push_back(to_string(ch));//1.把数字转换成字符串,拼接字符串,比较字典序
        }
        sort (str.begin(), str.end(), [](const string& s1, const string & s2)
        {
            return s1 + s2 > s2 + s1;//贪心的点在于每两个字符串都在两种顺序中选择最大的那个
        }
        );
        string n;
        for(auto& ch : str)
        {
            n += ch;
        }
        if(n[0] == '0')return "0";//处理前导零
        return n;
    }
};

这个排序规则为什么能排序

具有传递性

a b   > b a

b c >   c b

那么a c > c a(但是这里需要证明)

5.摆动序列

使用全局变量left,left 最开始设为 0 ,因为右边的点无论值为多少,第一个点都算

right 为右节点值减左节点值

left * right <= 0 计数加一

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) 
    {
        int left = 0;
        int size = nums.size();
        if(size == 1)return 1;
        int count = 0;
        for(int i = 0; i <= size - 2; i++)
        {
            int right = nums[i+1] - nums[i];
            if(right == 0)continue;
            if(left * right <= 0)count++;
            left = right;
        }
        return count + 1;
    }
};

即选取折点,贪心的点在于,无论是选取折点左边或折点右边的点,最终的节点数都可能更少

6.最长的递增子序列

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) 
    {
        vector<int> nums1;
        nums1.push_back(nums[0]);
        for(auto ch: nums)
        {
            if(ch > nums1.back())nums1.push_back(ch);
            int left = 0;
            int right = nums1.size()-1;
            while(left < right)
            {
                int mid = (left + right) / 2;
                if(ch > nums1[mid])left = mid +1;
                else right = mid;
            }
            nums1[left] = ch;//遍历过程中,用ch的值替换数组中大于它的最小值
        }
        return nums1.size();
    }
};

[7,3,8,4,7,2,14,13]
长度为1的序列的末尾值:7(x),3(x),2
长度为2的序列的末尾值:8(x),4,
长度为3的序列的末尾值:7,
长度为4的序列的末尾值:14(x),13

贪心的地方在于,可以接到7后面的肯定能接到3后面,可以接到3后面的肯定可以接到2后面。
(也因此这个数组是严格递增,因此可以使用二分查找)

这个数组的作用是记录最大的序列长度,比如说长度为1的序列末位置为2,4无法接在2后面,但是先前已经储存了接在3后面的序列了,就不需要担心序列长度丢失问题

7递增的三元子序列

思路同5,只需要判断三个就可以了

class Solution {
public:
    bool increasingTriplet(vector<int>& nums)
    {
        int a,b;
        a = nums[0];
        b = INT_MAX;
        for(int i = 0; i < nums.size();i++)
        {
            if(nums[i] < a)a = nums[i];
            if(nums[i] > a && nums[i] < b)b = nums[i];
            else if (nums[i] > b)return true;
        }
        return false;
    }
};

8.最长连续递增序列 

1 2 3 0 4
贪心的点在于,从1开始,到0处序列断开,那么我们不需要从2开始,因为从开始的序列长度一定小于从1开始。所以我们只需要记录最大值,然后从0再开始比较

class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        int counttmp = 1;
        int countmax = 1;
        for(int j = 1; j < nums.size();j++)
        {
            if(nums[j] > nums[j-1]){
              counttmp++;
              countmax = max(counttmp,countmax);
            }
            else
                counttmp = 1;
        }
        return countmax;
    }
};

9.买卖股票的最佳时机

贪心的点在于,我们每次寻找最小值只需要和下一个节点比较一次就可以了,因为我们已经储存了之前节点的最小值

class Solution {
public:
    int maxProfit(vector<int>& pr) {
        int pmin = INT_MAX;
        int money = 0;
        for(int i = 1; i < pr.size(); i++)
        {
            pmin = min(pmin, pr[i-1]);
            money = max(money, pr[i]-pmin);
        }
        return money;
    }
};

10.买股票的最佳时机2

贪心的点在于,只要出现正收益,我就交易 

1.分成一节一节

class Solution {
public:
    int maxProfit(vector<int>& pr) {
        int money = 0;
        for(int i = 0,j = 1; j < pr.size(); i++, j++)
        {
            if(pr[j]-pr[i]>0)money += pr[j]-pr[i];
        }
        return money;
    }
};

 2.双指针,整段求

class Solution {
public:
    int maxProfit(vector<int>& pr) {
        int money = 0;
        int n = pr.size();
        for(int i = 0;i < n;i++)
        {
            int j = i;
            while(j+1 < n && pr[j+1] > pr[j])//这里要注意判断j+1要小于n,不能越界
            {
                j++;
            }
            money += pr[j]-pr[i];
            i = j;
        }
        return money;
    }
};

11.k次取反后的最大化数组和

假设数组中负数为n个

1.n >= k 把数组中前k个小的负数转化成正数,再相加

2.n < k 先把数组中全部负数转换成正数,然后再计算k - n的值,如果为偶数,那么取正与取反抵消,如果为奇数,那么我们将最小的那个数取反即可 

class Solution {
public:
    int largestSumAfterKNegations(vector<int>& nums, int k) {
        int n = 0;
        int ret = 0;
        int MIN = INT_MAX;
        for(auto ch : nums)
        {
            if(ch < 0)n++;
            if(abs(ch) < MIN)MIN =abs(ch);
        }
        if(n >= k)
        {
            sort(nums.begin(), nums.end());
            for(int i = 0; i < k;i++)
            {
                ret += -nums[i];
            }
            for(int i = k; i < nums.size();i++)
            {
                ret+= nums[i];
            }
            return ret;
        }
        else
        {
            for(int i = 0;i < nums.size();i++)
            {
                ret += abs(nums[i]);
            }
            if((k-n)%2==0)return ret;
            else return ret-2*MIN;
        }
    }
};

12.按身高排序

. - 力扣(LeetCode)

class Solution {
public:
    vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
        int size = names.size();
        vector<int>arr(size);
        for(int i = 0; i < size;i++)
        {
            arr[i] = i;
        }
        sort(arr.begin(),arr.end(),[&](int i,int j)
        {
            return heights[i]>heights[j];
        });
        vector<string>ret(size);
        for(int i = 0; i < size; i++)
        {
            ret[i] = names[arr[i]];
        }
        return ret;
    }
};

是13题的前置提示,具体就是创建一个下标数组,然后根据身高的高低重新排序这个数组,最后将人名再填充到一个新的数组中

13.优势洗牌

. - 力扣(LeetCode)

class Solution {
public:
    vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
        int size = nums1.size();
        sort(nums1.begin(),nums1.end());//重新排序nums1
        vector<int>arr(size);
        vector<int>ret(size);
        for(int i = 0; i < size; i++)//同上题,进行下标排列
        {
            arr[i] = i;
        }
        sort(arr.begin(),arr.end(),[&](int i, int j)
        {
            return nums2[i] < nums2[j];
        });
        int left = 0;
        int right = size-1; //Left  与 right 用来指向当前arr最左边与最右边的元素
        for(int i = 0; i < size; i++)////定义一个i遍历新的nums1数组
        {
            if(nums1[i] > nums2[arr[left]])
            {
                ret[arr[left]] = nums1[i];
                left++;
            }
            else 
            {
                ret[arr[right]] = nums1[i];//Arr[left]  与arr[right]找到该数字相对原数组的 
                right--;                  //下标,再将nums1中的值放进ret中
               
            }
        }
        return ret;
    }
};

我们的贪心策略是从左往右比较,有两种情况

第一种例如上面8小于11,那么我们把8与最大的32配对,把最大的抵消掉

第二种例如 9   12

                   6    11

这里9比6大,直接把9与6配对,因为如果我们不这样做,而是把12与6配对,这样的话9比11小,我们就损失了一对优势

但是我们需要把8放到原数组中32对应的位置,因此需要使用arr[left] arr[right]取得这个数原数组的下标

14.最长回文串 

. - 力扣(LeetCode)

class Solution {
public:
    int longestPalindrome(string s) {
        vector<int>s1(128);//因为这里只有52个字母,那么直接开128个
        int size = s.size();
        int ret = 0;
        for(int i = 0; i < size; i++)//这个字母的阿斯克码值就对应新数组的下表,进行计数
        {
            s1[s[i]]++;
        }
        for(int i = 0; i < 128; i++)
        {
            ret+=s1[i]/2*2;//这里是一个化简操作,我们需要将偶数个排列在两边对称,奇数时会多一个, 
                           //使用/2向下取整
        }
        if(ret < size)return ret+1;//如果全为偶数ret= size,存在至少一个奇数时ret<size,此时我们 
                                    //可以在对称轴再放置一个字母
        else return ret;
    }
};

贪心策略是,假设有一条对称轴,两边能放几个就放几个,如果是偶数那么全放完,如果是奇数只能放偶数个,最后如果还有剩下的字母,还可以再对称轴再放一个 

15.增减字符串匹配

. - 力扣(LeetCode)

class Solution {
public:
    vector<int> diStringMatch(string s) {
    int size = s.size();
    vector<int>ret(size+1);
    int minnum = 0;
    int maxnum = size;
    for(int i = 0 ;i < size;i++)
    {
        if(s[i]=='I')
        {
            ret[i]= minnum;
            minnum++;
        }
        else
        {
            ret[i]= maxnum;
            maxnum--;
        }
    }
    ret[size]= minnum;
    return ret;
    }
};

贪心的点在于,如果是I,即这个数到下个数要增长,那么我们选取当前最小的那个数,可以使得出现增长的情况数目最多,同样,当我们判断到D,我们选取最大的那个数,可以使得出现减少的情况数目最多。

严格地说当我们采取最大或者最小的那个数,那么后面的排序一定是下降或者上升趋势的。

最后一个位置需要我们手动排,这时候minnum=maxnum,任意选一个加入即可

16.分发饼干

. - 力扣(LeetCode)

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        int sizeg = g.size();
        int sizes = s.size();
        int ret = 0;
        int i = 0;
        int j = 0;
        while(i < sizeg &&j < sizes)
        {
            if(s[j]>=g[i])
            {
                i++;
                j++;
                ret++;
            }
            else j++;
        }
        return ret;
    }
};

原理类似与13优势洗牌,我们把两个数组排序好,然后使用双指针依次同时向右即可,当饼干不能满足胃口时,直接丢弃饼干 

17.最优除法

. - 力扣(LeetCode)

class Solution {
public:
    string optimalDivision(vector<int>& nums) {
        int size = nums.size();
        string ret;
        if(size == 1)return to_string(nums[0]);
        else if(size == 2)
        {
            ret += to_string(nums[0]);
            ret += '/';
            ret += to_string(nums[1]);
        }
        else
        {
            ret += to_string(nums[0]);
            ret += '/';
            ret += '(';
            for(int i = 1; i < size -1; i++)
            {
                ret += to_string(nums[i]);
                ret += '/';
            }
             ret += to_string(nums[size - 1]);
             ret += ')';
        }
        return ret;
    }
};

这题主要是一个思路的问题,只要找到贪心的策略就比较简单了,只需要把数字填进去。

首先这么多数字相除a/b/c/d/e/f....

最后肯定会化成x/y,我们只需要使x最大,y最小即可,再观察式子,我们可以知道a肯定在分子上,而b无论括号怎么加,肯定在分母中。因此我们贪心地想,只需要把cdef....放在分子上即可,那么我们只需要在这样添加括号a/(b/c/d/e/f...),最后cdef....都会翻到分子上

18.跳跃游戏

 . - 力扣(LeetCode)

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int left = 0;
        int right = 0;
        int maxpos = 0;
        int ret = 0;
        int size = nums.size();
        while(left <= right)
        {
            if(maxpos >= size -1)
            {
                return true;
            }
            for(int i = left; i <= right; i++)
            {
                maxpos = max(maxpos,i+nums[i]);
            }
            ret++;
            left = right + 1;
            right = maxpos;
        }
        return false;
    }
};

这题实际上并不是严格使用贪心的而是使用层序遍历的思想

例如一个数组[2,3,1,1,4]

它开始时的左下标 =右下标 =0

然后从左下标开始遍历到右下标,i+nums[i]中的最大下标就是最远距离,也就是下一次遍历的右端点

下一次的左端点假设是right + 1。但是有可能跳不到,比如0 1 2 3第一次跳跃最远距离是0.

所以 2 3 1 1 4 被我们分成了

2 | 3 1| 1 4他们分别是第一次第二次第三次可以跳跃到的范围

 19.跳跃游戏2

. - 力扣(LeetCode)

代码思路类似上一题

class Solution {
public:
    int jump(vector<int>& nums) {
        int left = 0;
        int right = 0;
        int maxpos = 0;
        int ret = 0;
        int size = nums.size();
        while(1)
        {
            if(maxpos >= size -1)
            {
                return ret;
            }
            for(int i = left; i <= right; i++)
            {
                maxpos = max(maxpos,i+nums[i]);
            }
            ret++;
            left = right + 1;
            right = maxpos;
        }
    }
};

20.加油站

. - 力扣(LeetCode)

我们先把gas-cos,得到从这个加油站到下个加油站的净收益ret,如果小于0那么无法到下一个位置,首先我们会想到使用暴力解法,即从第一个位置开始遍历,在这个位置到向后size个位置

将每一个位置的ret累加进入count中,当count小于0时说明无法完成一周,我们break,在跳出后我们有两种情况,一种是count<0跳出,另一种是完成循环,count >= 0,因此进行一次判断,如果成功直接返回i的值

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int size = gas.size();
        vector<int>ret(size);
        for(int i = 0; i < size;i++)
        {
            ret[i] = gas[i]-cost[i];
        }
        for(int i = 0; i < size;i++)
        {
            int count = 0;
            for(int step = 0; step < size; step++)
            {
                int index =(i+step)%size; 
                count += ret[index%size];
                if(count < 0)break;
            }
            if(count >= 0)return i;
        }
        return -1;
    }
};

但是上面的方法时间复杂度太高了

我们可以知道

如果我们跑到e

a + b + c +d +e < 0

因为我们已经成功跑完abcd了所以

a >=0 

a+b >= 0

a+b+c >= 0

a +b +c +d >=0

所以我们有

b+c+d+e < 0

c+d+e <0

d+e <0

e <0

因此从b到e我们都无法成功走完。

因此我们从f开始继续遍历

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int size = gas.size();
        vector<int>ret(size);
        for(int i = 0; i < size;i++)
        {
            ret[i] = gas[i]-cost[i];
        }
        for(int i = 0; i < size;i++)
        {
            int count = 0;
            int step;
            for(step = 0; step < size; step++)
            {
                int index =(i+step)%size; 
                count += ret[index%size];
                if(count < 0)break;
            }
            if(count >= 0)return i;
            i = i + step;
        }
        return -1;
    }
};

 a  b  c  d e f g

关于时间复杂度

当站点为a,我们仅遍历一次数组,复杂度N

当站点为b,我们先遍历了a-a,,再遍历了一次数组复杂度N+1

当站点为c,我们遍历了a-b,再遍历了一次数组复杂度N+2

最差的情况是g为开始的站点,时间复杂度为2N-1,即o(n)

迪杰斯特拉算法:从原理到数学建模实战应用 最短路径问题是图论中的经典问题,旨在寻找图中两点之间成本最低的路径。其核心原理通常基于贪心或动态规划思想,通过逐步迭代逼近最优解。迪杰斯特拉算法作为解决非负权图单源最短路径问题的代表,因其清晰的贪心策略和较高的效率,在工程实践中具有重要价值。该算法广泛应用于网络路由、地图导航、物流配送等场景,通过将实际问题抽象为图模型,并定义合适的边权值(如距离、时间、成本),能够为资源调度和路径规划提供精确解。本文深入剖析了迪杰斯特拉算法的贪心思想与手动模拟过程,并详细对比了其朴素实现与堆优化实现的复杂度。针对数学建模竞 阅读详情

相关推荐

【信息科学与工程学】【数据科学】数据科学领域 第六篇 算法设计 07 堆、栈、表、矩阵、集合、队列、数组、字符串、树、图、动态规划、结构体、元组的算法01

当前段必须包含所有字符的最后出现位置。1. 字符串分割成最多片段2. 基因序列功能域划分3. 文本段落划分4. 音频声道分离5. 图像色彩分区6. 社交网络社群划分7. 蛋白质结构域8. 音乐乐章分段9. 代码模块划分10. 章节划分特征:一次扫描,贪心确定边界。

weixin_49199313的博客 1293

Java编程:贪心算法

Java编程:贪心算法

KaiSarH 1388

告别Keil!用VSCode+GCC+CMake搭建STM32开发环境(STM32F103实战)

本文详细介绍了如何从Keil迁移到VSCode+GCC+CMake的现代化STM32开发环境,以STM32F103为例,涵盖环境配置、工程迁移、CMake构建、调试下载等关键步骤。通过开源工具链,开发者可以显著提升编译效率,实现跨平台开发,同时降低商业软件授权成本。

dida4700的博客 439

贪心算法集锦

1.普通贪心 2.进阶版贪心:(1)最小生成树 (2)HUMAN编码 (3)模拟退火 首先我们应该了解什么是贪心算法:贪心算法也就是得到在某种意义上的局部最优解,不是对所有问题 ...

qq_57657120的博客 1075

告别TwinCAT:手把手教你用IgH EtherCAT Master在LinuxCNC上搭建实时运动控制平台

本文详细介绍了如何利用IgH EtherCAT Master和LinuxCNC搭建开源实时运动控制平台,替代商业软件TwinCAT。通过分步指南,包括实时Linux环境配置、EtherCAT主站安装、LinuxCNC集成及多轴同步控制实现,帮助开发者构建高性能、低成本的工业自动化解决方案。

weixin_42641741的博客 406

【保研面试】线性代数面试复习

线性相关和无关 有向量组A,a1,a2…an , 如果存在不是全为0的k1,k2…kn,满足 a1 * k1 + a2 * k2… an * kn = 0 则向量组A称为线性相关(可以跟向量组A共面联系,即可以通过几个向量,表示出另外几个向量,故称为线性相关) 极大线性无关组 设有向量组A a1,a2…an(本身为线性相关) :若选出r个向量,满足以下条件 (1)向量组 r : 线性无关; (2) 向量组A中任意r+1个向量(若有的话)都线性相关, 则向量组r 是向量组A的一个极大线性无关组(简称为

云端筑梦师 6312

贪心算法(集合覆盖问题)

贪心算法 代码实现 package greedy; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class GreedyAlgorithm { public static void main(String[] args) { //创建广播电台,放入到Map ...

sparky的博客 1538

无人机避障——卡内基梅隆大学(CMU)CERLAB 无人机自主框架复现

CMUCERLAB无人机自主框架是一个模块化的无人机自主导航系统,包含感知、测绘、规划和控制等组件。安装过程中遇到的主要问题包括:(1)cv_bridge路径未正确识别,需手动指定路径;(2)OpenCV版本冲突(4.2与4.6),导致动态导航节点崩溃。解决方案包括:完全卸载OpenCV4.2,重新编译安装OpenCV4.6,并修改相关CMakeLists文件指定版本。最终成功运行仿真环境,实现无人机在Gazebo和RViz中的自主避障导航功能。

weixin_45390670的博客 1650

使用贪心算法解决集合覆盖问题

在《算法图解》里面有一个蛮有意思的小案例,背景是一个广播节目,要让全美的50个周的听众都能够听到,但是每个电台可能覆盖多个州,每在一个电台播出就需要一笔费用,所以就是从成本的角度...

congbao6525的博客 2120

攀藤PMS系列传感器STM32驱动开发与数据解析实战

本文详细介绍了攀藤PMS系列传感器与STM32微控制器的驱动开发与数据解析实战,涵盖硬件连接、数据协议解析、驱动源码编写及数据处理优化。重点解析了传感器数据帧结构,提供了完整的STM32驱动实现代码,并分享了实际应用中的问题排查与性能优化经验,帮助开发者快速实现高精度颗粒物浓度检测。

milk8的博客 358

GeoServer改造Springboot源码一(公共部分)

今天开始开启关于GeoServer的一个全新系列,主要是把改造Springboot后的详细代码粘贴出来,此文应配合《》系列共同阅读,按照前系列的时间顺序结合此系列的源码展示可以快速构建GeoServer功能的二次封装的后端系统。

龙井的专栏 1905

贪心算法-合集

贪心算法1:贪心的概念 https://blog.csdn.net/yanyanwenmeng/article/details/83005293 贪心算法2:背包问题 https://blog.csdn.net/yanyanwenmeng/article/details/83008780 贪心算法3:会议安排 https://blog.csdn.net/yanyanwenmeng/article/...

zgwzgw的博客 280

10万+字超硬核 机器学习 笔记(面试八股)

10w字总结面试中可能用到的机器学习八股和常用算法,包括感知机(Perceptron)、多层感知机(MLP, Multi-Layer Perceptron)、支持向量机(SVM, Support Vector Machine)、K 最近邻(KNN, K-Nearest Neighbors)、朴素贝叶斯(Naive Bayes)、决策树(Decision Tree)、随机森林(Random Forest)、Bagging、Boosting、GBDT、XGBoos、LightGBM等。

haopinglianlian的博客 4670

详解PAT甲级1033 贪心算法

分数 25。

qq_62368250的博客 440

云原生之容器编排实践-在K8S集群中使用Registry2搭建私有镜像仓库

基于前面搭建的3节点 Kubernetes 集群,今天我们使用 Registry2 搭建私有镜像仓库,这在镜像安全性以及离线环境下运维等方面具有重要意义。作为测试环境,本次使用 Registry2 搭建了私有镜像仓库,实际生产环境建议使用 Harbor;创建了一个 local-storage 的 StorageClass ,并使用本地磁盘的方式创建使用 PV ,实际建议使用 NFS 。

Heartsuit的博客 2469

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Day29 贪心算法 part03

第三种是20,这时候就要用到贪心算法了,我们要先使用10+5的组合,因为5元更加灵活,如果前面一种不行,然后再判断 5x3的组合。如果sum为负数,更新为0后,加上下一个值还是负数,那就会再次更新起点。5.总的来说,这道题坚持的原则就是出现sum为负数,说明[0, i]区间都不能作为起始位置,因为这个区间选择任何一个位置作为起点,到i这里都会断油,那么起始位置从i+1算起,再从0计算sum。经过前后两次遍历,取最大值之后,就可以从局部最优推出了全局最优,即:相邻的孩子中,评分高的孩子获得更多的糖果。

2401_83448199的博客 1473

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

贪心算法集合

贪心的本质:是选择每一阶段的局部最优,从而达到全局最优。

puzzleOO的博客 210

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

JS算法面试题题目集合(后面文章具体详解,不断更新)

 1.验证一个数是否是素数   2.斐波那契   3.求最大公约数   4.数组去重   5.删除重复的字符   6.排序两个已经排好序的数组   7.字符串反向   8.字符串原位反转   9.判断是否是回文   10.判断数组中是否有两数之和   11.连字符转成驼峰   12.加油站问题-贪心算法 一辆汽车加满油后可行驶n公里。旅途中有若干个加油站。设计一个有效算法,指出应在哪些加油站停靠加油,使沿途加油次数最少。对于给定的n(n <= 5000)和k(k <= 1

dream_start_at_2017的博客 918

6. 贪心算法深度解析

本文系统解析了贪心算法的核心思想与应用场景,重点介绍了贪心算法的定义、基本步骤、适用条件以及正确性证明方法。通过Python代码示例展示了活动选择、分数背包、找零钱、哈夫曼编码、最小生成树等经典问题的贪心解法。文章还对比了贪心与动态规划的区别,指出贪心算法的常见陷阱,并提供了思维训练建议。贪心算法在具备最优子结构和贪心选择性质的问题中能以较低时间复杂度获得精确解,但需要谨慎验证其适用性。

m0_46786082的博客 382

985研一学习日记 - 2024.11.10

一个人内耗,说明他活在过去;一个人焦虑,说明他活在未来。只有当一个人平静时,他才活在现在。

LiuYQi的博客 1088

【PAT甲级 - C++题解】1033 To Fill or Not to Fill

📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!

Newin2020的博客 712

算法题-hot100学习总结

针对于上题,本题采用一维数组(滚动数组);将二维数组压缩至一维,这里一维指的是将上一层dp[i-1]的值拷贝到dp[i]中;故递推公式:dp[j]=max(dp[j],dp[j-weight[i]]+value[i]);3、初始化:对其可全部初始化为非负最小值;4、遍历顺序采用倒序遍历,正序会将前一个的物品价值重复使用,且遵循先遍历for物品再遍历for背包;

m0_69666329的博客 553

机试和面试注意事项

4.调用类的方法时忘记写调用者了,格式写成了调用测试类里面的方法了。2.this.name会漏掉.1.测试类没写主函数main。

qq_75162624的博客 231

贪心算法(集合覆盖问题)

一、贪心算法概述 贪心算法的核心思想可以总结为:贪心算法总是作出在当前看来最好的选择。 也就是说贪心算法并不从整体最优考虑,它所作出的选择只是在某种意义上的局部最优选择。当然,希望贪心算法得到的最终结果也是整体最优的。 虽然贪心算法不能对所有问题都得到整体最优解,但对许多问题它能产生整体最优解,如单源最短路经问题,最小生成树问题等。虽然在一些情况下,即使贪心算法不能得到整体最优解,但其最终结果却是最优解的很好近似。 二、集合覆盖问题 2.1 问题描述 假设你办了个广播节目,要让国内的 8 个重要城市的听

Ronz 的博客 5750

leetcode 贪心算法 集合

44. Wildcard Matching 模糊匹配问题 思路很简单:从头开始匹配,遇到“*”就在字符串s中继续找能够匹配字符串p的下一个字符的字符,同时需要记住当前星号的位置,以便回溯。 bool isMatch(string s, string p) { int sl=s.size(),pl=p.size(); int i=0,j=0; int lasts=-1,las...

肥肥很菜 512
上一篇: 基础动态规划算法集合(更新到26.环绕字符串中唯一的子字符串)
下一篇: 进程的等待
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值