Understanding change-making algorithm

后端 未结 4 1978
礼貌的吻别
礼貌的吻别 2020-12-01 08:07

I was looking for a good solution to the Change-making problem and I found this code(Python):

target = 200
coins = [1,2,5,10,20,50,100,200]
ways = [1]+[0]*ta         


        
4条回答
  •  心在旅途
    2020-12-01 09:05

    The solution that you posted is summarized version of this code.

        /// 
        /// We are going to fill the biggest coins one by one.
        /// 
        ///  the amount of money 
        public static void MakeChange (int n)
        {
            int n1, n2, n3; // residual of amount after each coin
            int quarter, dime, nickel; // These are number of 25c, 10c, 5c, 1c
            for (quarter = n/25; quarter >= 0; quarter--)
            {
                n1 = n - 25 * quarter;
                for (dime = n1/10; dime >= 0; dime--)
                {
                    n2 = n1 - 10 * dime;
                    for (nickel = n2/5; nickel >= 0 && (n2 - 5*nickel) >= 0; nickel--)
                    {
                        n3 = n2 - 5 * nickel;
                        Console.WriteLine("{0},{1},{2},{3}", quarter, dime, nickel, n3); // n3 becomes the number of cent.
                    }
                }
            }
        }
    

提交回复
热议问题