zoukankan      html  css  js  c++  java
  • 找钱问题

      现有M元,a个10元,b个5元,c个1元,寻找一种钱正好凑成m的组合。

    两种方式实现:1、一种穷举法,2、可以利用取整取余更高效,

    还有一种可以利用堆栈来实现,这个我想用c实现,但是目前只是想法没有具体代码,前2种代码如下:

    package com.hs.datastructure;
    public class DataStruct {
        public static void main(String[] args) {
            findCombonation(133, 7, 11, 100);
            findCombonation1(133, 7, 11, 100);
        }
        
        public static void findCombonation(int M,int a,int b,int c){
            int x,y,z=0;
            if(M>10*a+5*b+c){
                System.out.println("钱不够");
                return;
            }
            if(M/10<=a){
                x = M/10;
            }else{
                x = a;
            }
            M -= x*10;
            if(M/5<=b){
                y=M/5;
            }else{
                y=b;
            }
            z = M - y*5;
            if(z>c){
                System.out.println("凑不齐");
                return;
            }
            System.out.println("x:"+x+","+"y:"+y+","+"z:"+z);
        }
        public static void findCombonation1(int M,int a,int b,int c){
            int x,y,z,sum=0;
            if(M>10*a+5*b+c){
                System.out.println("钱不够");
                return;
            }
            for(x=1;x<=a;){
                sum = 10*x;
                if(sum>M){
                    x--;
                    break;
                }else{
                    if(x==a)break;
                    x++;
                }
            }
        
            M -= 10*x;
            for(y=1;y<=b;){
                sum = 5*y;
                if(sum>M){
                    y--;
                    break;
                }else{
                    if(y==b)break;
                    y++;
                }
            }
            z = M- 5*y;
            if(z>c){
                System.out.println("凑不齐");
                return;
            }
            System.out.println("x:"+x+","+"y:"+y+","+"z:"+z);
        }
    }
    这个只不过是自己的流水账,偶尔有一些心得,错误的地方概不负责
  • 相关阅读:
    java匿名对象
    Java面向对象详解
    Java语言基本语法
    Win7下JDK环境变量的设置
    LeetCode-Shortest Word Distance
    LeetCode-Count Complete Tree Nodes
    LeetCode-Palindrome Pairs
    LeetCode- Implement Trie (Prefix Tree)
    LeetCode-Lowest Common Ancestor of a Binary Tre
    LeetCode- Binary Tree Longest Consecutive Sequence
  • 原文地址:https://www.cnblogs.com/ashitaka/p/5913403.html
Copyright © 2011-2022 走看看