入門級貪心演算法——java實現

來源:互聯網
上載者:User

標籤:ted   back   視頻   package   class   new   util   create   公式   

貪心演算法入門

貪心演算法是一種思路,而不是一種公式。

認真看,一會兒就會了!

個人網站:多貓影視(能看各大vip視頻)www.duomao.xyz

package com.niu.test;import java.util.Scanner;/** * Created by Administrator on 2017/9/28. */public class TanXin1 {    /**     * 貪心演算法,找零錢     * 假設有100 50 10 1零錢供找零,輸入找零的錢返回找零的錢和張數     *      * 思路:     * while(能朝給定目標前進一步){     *  利用可行的決策,求出可行解的一個元素     * }     * 由所有元素組合成問題的一個可行解;     * 這裡我沒有提現結果的組合,直接進行了列印輸出。     * 迴圈的思路:     * 1、從100元開始找零直到1元:while (i <= (a.length - 1))      * 2、判斷當前找零的錢是否大於剩餘要找零的錢(不然找零為負數):count >= a[i],如果小於count則換到下一個面額的貨幣     * 3、輸出找零的錢和張數:System.out.println("找零:" + a[i] + "元" + count / a[i] + "張。");     * 4、如果剩餘錢數為0則找零結束否則i+1換到下一個貨幣值     *      * @param args     */    public static void main(String[] args) {        while (true) {            int[] a = {100, 50, 10, 5, 1};            System.out.println("輸入找零的錢:");            Scanner sc = new Scanner(System.in);            //count  總錢數            int count = sc.nextInt();            //i  總共的貨幣種類            int i = 0;            while (i <= (a.length - 1)) {                //沒有找的零錢大於a[i]的時候執行找零錢                if (count >= a[i]) {                    System.out.println("找零:" + a[i] + "元" + count / a[i] + "張。");                    //剩餘count等於count減去已經找零的金額。                    count = count - count / a[i] * a[i];                    if (count == 0) {                        System.out.println("找零完畢!");                        break;                    } else {                        i++;                    }                } else {                    i++;                }            }        }    }}
 結果:

 

入門級貪心演算法——java實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.