贪心算法案例

贪心算法

贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,算法得到的是在某种意义上的局部最优解

零钱兑换(力扣322 )

class Solution {
    int minCount=Integer.MAX_VALUE;
    public int coinChange(int[] coins, int amount) { 

        Arrays.sort(coins); 
        dfs(coins,amount,0,coins.length-1); 
        if (minCount == Integer.MAX_VALUE) return -1; 
        return minCount; 
    }
    public void dfs (int[] coins,int amount,int selectedCount,int startIndex) { 
     
        if (amount==0) { 
            if (selectedCount < minCount) { 
                minCount = selectedCount; 
            }
            return; 
        }
        if (startIndex<0) { 
            return; 
        }
      
        int maxCount = amount / coins[startIndex]; 
      
        for (int i=maxCount;i>=0 && i+selectedCount < minCount ;i--) { 

            int resAmount = amount - i*coins[startIndex]; 
            dfs(coins,resAmount,selectedCount+i,startIndex-1);  
        } 
    }
}

玩筹码(力扣1217)

尽量使用代价为 0 的方法移动筹码,再用代价为 1 的方法移动

class Solution {

    public int minCostToMoveChips(int[] position) {

        int n = position.length;

        int odd = 0, even = 0;
        for (int i=0;i<n;i++) {

            if ((position[i] & 1) == 1) odd++;
            else even++;
        }
        return Math.min(odd, even);
    }
}

跳跃游戏(力扣55)

public class Solution {
    public boolean canJump(int[] nums) {
        int n = nums.length;
        int rightmost = 0;
        for (int i = 0; i < n; ++i) {
            if (i <= rightmost) {
                rightmost = Math.max(rightmost, i + nums[i]);
                if (rightmost >= n - 1) {
                    return true;
                }
            }
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值