/* 购物券消费方案
公司发了某商店的购物券1000元,限定只能购买店中的m种商品。
每种商品的价格分别为m1,m2,…,要求程序列出所有的正好能消费完该购物券的不同购物方法。
程序输入:
第一行是一个整数m,代表可购买的商品的种类数。
接下来是m个整数,每个1行,分别代表这m种商品的单价(0<m<1000)。
程序输出:
第一行是一个整数,表示共有多少种方案
第二行开始,每种方案占1行,表示对每种商品购买的数量,中间用空格分隔。
例如:
输入:
2
200
300
则应输出:
2
2 2
5 0
输入:
2
500
800
则应输出:
1
2 0
输入:
1
999
则应输出:
0
多个方案间的顺序不重要*/
import java.util.Arrays;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class 购物券消费方案 {
public static int price[]; // 保存每种商品的单价
public static int result[]; // 保存每种商品购买的数量
public static int num; // 购买的商品的种类数
public static List<int[]> list = new ArrayList<int[]>();
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
if (num == 0)
return;
price = new int[num];
result = new int[num];
for (int i = 0; i < num; i++) {
result[i] = 0; // 初始化每种商品购买的数量
}
for (int i = 0; i < num; i++) {
price[i] = scan.nextInt(); // 输入每种商品的单价
}
cal(1000, 0);
System.out.println(list.size()); // 元素个数
for (int[] resu : list) { // 输出结果
for (int n : resu) {
System.out.print(n + " ");
}
System.out.println();
}
}
public static void cal(int money, int cur) {
if (money < 0)
return;
else if (money == 0) {
int[] temp = new int[num];
for (int j = 0; j < temp.length; j++) {
temp[j] = result[j];
}
list.add(Arrays.copyOf(temp, temp.length));
return;
} else
for (int i = cur; i < num; i++) {
result[i]++;
cal(money - price[i], i);
result[i]--;
}
}
}
/*import java.util.Arrays;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class 购物券消费方案 {
public static int price[]; // 保存每种商品的单价
public static int result[]; // 保存每种商品购买的数量
public static int max_result[]; // 保存每种商品购买的最多数量
public static int num; // 购买的商品的种类数
public static List<int[]> lis = new ArrayList<int[]>();
public static void print() {
for (int[] x : lis) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
// 检测符合条件的组合
public static boolean check(int[] price, int[] result) {
int sum = 0;
for (int i = 0; i < price.length; i++) {
sum += price[i] * result[i];
}
if (sum == 1000) {
return true;
}
return false;
}
public static void f(int begin, int end) {
if (begin >= end) {
if (check(price, result)) { // 检测符合条件的组合 将数组添加到lis列表
lis.add(Arrays.copyOf(result, result.length));
}
return;
}
for (int i = 0; i <= max_result[begin]; i++) {
result[begin] = i; // 保存当前i的值
f(begin+1,end); // 迭代
result[begin] = 0;//还原
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
price = new int[num];
result = new int[num];
max_result = new int[num];
for (int i = 0; i < num; i++) {
price[i] = scan.nextInt(); // 输入每个商品价格
max_result[i] = 1000 / price[i]; // 记录每种商品的最多个数
}
f(0,num);
if (lis.size() == 0) { // 没有元素
System.out.println(0);
} else {
System.out.println(lis.size()); // 元素个数
print(); // 输出结果
}
}
}*/
运行结果:
2
200
300
2
5 0
2 2
购物券消费方案
最新推荐文章于 2023-06-20 21:55:40 发布