找钱问题

  现有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);
    }
}

 

posted @ 2016-09-27 16:38  麦哈顿博士  阅读(241)  评论(0编辑  收藏  举报