平安科技2017筆試題目
阿新 • • 發佈:2019-02-12
題目要求見圖片,可放大瀏覽器檢視!
程式碼見下面,無重複分類遞迴解決,效率還可以!
package others;
import java.util.Scanner;
public class CoinCoinPingAn {
public static void main(String[] args) {
// 從命令列讀取資料
Scanner in = new Scanner(System.in);
String s1 = in.nextLine();
String[] s2 = s1.split("\\=|," );
int n = Integer.parseInt(s2[1]); //總的錢數目
int[] num = new int[6]; //這是每個錢的數目
for(int i = 3; i < s2.length; i = i + 2) {
num[i/2 - 1] = Integer.parseInt(s2[i]);
}
int times = coinCoinPingAn(n, num); //總的拼湊次數
System.out.println(times);
}
private static int coinCoinPingAn(int n, int[] num) {
int[] coinValue = {1, 5, 10, 20, 50, 100};
int m = coinValue.length - 1;
int times = coinCoinPingAn(n, coinValue, m, num);
return times;
}
private static int coinCoinPingAn(int n, int[] coinValue, int m, int[] num) {
if (n == 0){
return 1;
}
if(n < 0) {
return 0;
}
if(m < 0) {
return 0;
}
int times_temp = 0;
for(int i = 0; i <= num[m]; i++) {
times_temp = times_temp + coinCoinPingAn(n - i*coinValue[m], coinValue, m -1, num);
}
return times_temp;
}
}
執行效果:
n=100,a1=0,a2=0,a3=5,a4=6,a5=3,a6=2
8