算法学习之- 贪心算法

来源:互联网 发布:平面设计软件百度云 编辑:程序博客网 时间:2024/05/29 10:35

一、什么是贪心算法?

        贪心算法是指在对问题求解的时候,总是做出当前看来你是做好的选择。即不从整体最优加以考虑,只做出在某种意义上的局部最优。

二、解题步骤

1:建立数学模型描述问题

2:把问题的求解分解成若干个子问题

3:对每一个子问题求解,得到子问题的局部最优解

4:把子问题的局部最优解合成原来问题的一个解。

三、例子:

1:活动选择问题:n个需要在同一天使用同一个教室的活动a1,a2,…,an,教室同一时刻只能由一个活动使用。每个活动ai都有一个开始时间si和结束时间fi。一旦被选择后,活动ai就占据半开时间区间[si,fi)。如果[si,fi][sj,fj]互不重叠,aiaj两个活动就可以被安排在这一天。该问题就是要安排这些活动使得尽量多的活动能不冲突的举行 。

         方案: 贪心算法中策略的选择很重要。这个例子中我们面临以下的选择:

a: 每次选择开始时间最早的   b:每次选择持续时间最短的  c: 每次选择结束时间最早的。可以用数学归纳法证明,选择c方案是最好的。

2:找零问题: 假设1元、2元、5元、10元、20元、50元、100元的纸币分别有c0, c1, c2, c3, c4, c5, c6张。现在要用这些钱来支付K元,至少要用多少张纸币?用贪心算法 思想,很显然,每一步尽可能用面值大的纸币即可。

       3:leetcode 中的t452 

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

这个题目也是一个贪心算法的例子,优先按照起点的位置排序,在起点相同的时候按照结束的位置排序。

代码:

public class Solution {    public int findMinArrowShots(int[][] points) {        if(points==null || points.length==0) return 0;    //优先按照起点位置排序,然后按照结束位置排序    Arrays.sort(points, ( x , y) -> x[0] == y[0] ? x[1] - y[1] : x[0] -y[0]);    int count = 1;    int arrowLimit = points[0][1];    //贪心法,基于上一个箭,记录当前能够射穿的所有    for(int i=1;i<points.length;i++) {        if(points[i][0]<=arrowLimit) {            arrowLimit=Math.min(arrowLimit, points[i][1]);        } else {            count++;            arrowLimit=points[i][1];        }    }    return count;    }}

         


0 0
原创粉丝点击