google笔试题 人民币问题

方法一:递归方法
对 charge[]={1,5,10,20,50,100}标号 用i表示 0,1,2,3,4
f(n,i)表示n由后面第i到4种零钱的组合结果
f(n,0)=f(n-charge[0],0)+f(n-charge[1],1)+f(n-charge[2],2)+f(n-charge[3],3)+f(n-charge[4],4)

f(n,i)=f(n-charge[i],i)+...+f(n-charge[4],4)

public class Money {

	public static int[] charge = { 1, 5, 10, 20, 50, 100 };

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int sum = 100;
		int m = money(sum, 0, sum + "=");
		System.out.println(m);
	}

	public static int money(int n, int s, String path) {
		if (n == 0) {
			System.out.println(path);
			return 1;
		}
		int count = 0;
		for (int i = s; i < charge.length; i++) {
			if (n >= charge[i]) {
				count += money(n - charge[i], i, path+ charge[i] + "+" );
			}
		}
		return count;
	}
}



方法二:暴力破解法
package com.viking.dynamic;

public class Money2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(money(100));
	}

	public static int money(int n) {
		int count = 0;
		for (int i = n % 5; i <= n; i += 5) {
			int f = n - i;
			if (f == 0) {
				count++;
				print(n, i, 0, 0, 0, 0, 0);
			} else if (f % 5 == 0) {
				for (int j = 0; j <= f; j += 5) {
					int g = f - j;
					if (g == 0) {
						count++;
						print(n, i , j, 0, 0, 0, 0);
					} else if (g % 10 == 0) {
						for (int k = 0; k <= g; k += 10) {
							int h = g - k;
							if (h == 0) {
								count++;
								print(n, i, j, k, 0, 0, 0);
							} else if (h % 10 == 0 ) {
								for (int t = 0; t <= h; t += 20) {
									int l = h - t;
									if (l == 0) {
										count++;
										print(n, i , j, k, t, 0, 0);
									} else if (l % 50 == 0) {
										for (int r = 0; r <= l; r += 50) {
											int p = l - r;
											if (p == 0) {
												count++;
												print(n, i , j, k, t, r, 0);
											} else if (p % 100 == 0) {
												count++;
												print(n, i , j, k, t, r, p);
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		return count;
	}

	public static void print(int n, int n1, int n5, int n10, int n20, int n50,
			int n100) {
		String path = n + "=";
		boolean change = false;
		if (n1 != 0) {
			path += "1*" + n1 / 1;
			change = true;
		}
		if (n5 != 0) {
			if (change) {
				path += "+";
			}
			path += "5*" + n5 / 5;
			change = true;
		}
		if (n10 != 0) {
			if (change) {
				path += "+";
			}
			path += "10*" + n10 / 10;
			change = true;
		}
		if (n20 != 0) {
			if (change) {
				path += "+";
			}
			path += "20*" + n20 / 20;
			change = true;
		}
		if (n50 != 0) {
			if (change) {
				path += "+";
			}
			path += "50*" + n50 / 50;
			change = true;
		}
		if (n100 != 0) {
			if (change) {
				path += "+";
			}
			path += "100*" + n100 / 100;
			change = true;
		}
		System.out.println(path);
	}
}

你可能感兴趣的:(人民币凑数问题)