找零錢問題

咱們知道人民幣有一、二、五、十、20、50、100這幾種面值。如今給你n(1≤n≤250)元,讓你計算換成用上面這些面額表示且總數不超過100張,共有幾種。好比4元,能用4張1元、2張1元和1張2元、2張2元,三種表示方法。java

樣例輸入:
1
4
0
樣例輸出:
1
3
import java.util.Scanner;

public class Main
{

	public static int[] moneyArray = { 1, 2, 5, 10, 20, 50, 100 };
	public static int sum = 0;

	public static void main(String[] args)
	{

		Scanner sc = new Scanner(System.in);
		while (sc.hasNext())
		{
			String str = sc.nextLine();

			if (str.equals("0"))
			{
				break;
			}
			sum = 0;
			f(Integer.parseInt(str), 0, 0);
			System.out.println(sum);

		}
		sc.close();

	}

	/**
	 * 
	 * @param value
	 * @param level
	 *            從0開始
	 */
	public static void f(int value, int level, int iStart)
	{

		if (value < 0 || level >= 100)
		{
			return;
		}
		else if (value == 0 && level < 100)
		{
			sum++;
		}
		else
		{
			for (int i = iStart; i < moneyArray.length; i++)
			{
				f(value - moneyArray[i], level + 1, i);
			}

		}

	}
}
相關文章
相關標籤/搜索