动态编程货币变化

时间:2017-05-31 18:32:49

标签: dynamic-programming

我有两个函数递归和迭代来计算货币变化;在迭代版本中我需要检查钱是否是变化的倍数(货币模数变化为零):有没有办法在不检查模数的情况下进行迭代?

  public static int MoneyChangeRecur(int money, int[] changes)
    {             
        int minChange = 0;

        if (money == 0) return 0;
        int min = int.MaxValue;
        for (int i = 0; i < changes.Length; i++)
        {


            if (money >= changes[i])
            {
               minChange = MoneyChangeRecur(money - changes[i], changes);
              if (minChange + 1 <= min)
                {
                    min = minChange + 1;
                }
            }
        }
        return min;
    }

    static  int IterativeMoneychange(int money)
    {
        int[] ar = new int[money + 1];
        int[] change = { 6, 5, 1 };
        int min = 9999;
        int index = 0;
        for (int i = 0; i < money+1; i++)
        {

            min = 99999;
            index = 0;
            bool modSet = false;
            for (int j= 0; j <change.Length; j++)
            {

                if (i >= change[j])
                {
                   int mod=(i % change[j]);

                    if(mod==0&&change[j]!=1)
                  {
                      if (!modSet) min = 99999;
                     if ((i-change[j] )< min)
                    {
                        min = (i - change[j]);
                        modSet = true;
                    }
                 }
                    else
                    {
                        if ((i - change[j]) < min)
                        {
                            min = (i - change[j]);
                            modSet = false;

                        }
                    }
                }


            }
            if (min != 99999)// min = 0;
            ar[i] = ar[min] +1;
        }

        return ar[money];

    }enter code here

0 个答案:

没有答案