华为OD题目:硬件产品销售方案
知识点递归数组DFS搜索回溯
时间限制: 1s 空间限制: 256MB 限定语言: 不限
题目描述:
某公司目前推出了AI开发者套件、AI加速卡、AI加速模块、AI服务器、智能边缘多种硬件产品,每种产品包含若干个型号。
现某合作厂商要采购金额为amount元的硬件产品搭建自己的AI基座。假设当前库存有N种产品,每种产品的库存量充足,
给定每种产品的价格,记为price (不存在价格相同的产品型号)。请为合作厂商列出所有可能的产品组合。
输入描述:
输入包含采购金额amount和产品价格列表price。第一行为amount,第二行为price。例如:
500
[100,200,300,500]
输出描述:
输出为组合列表。例如:
I[500], [200, 3001, [100, 200, 200], [100, 100, 3001, [100, 100, 100, 200, [100, 100, 100, 100, 1001
补充说明:
1.对于给定输入,产品组合少于150种。输出的组合为一个数组,数组的每元素也是一个数组,表示一种组合方案。如果给定产品无法组合金额为amount元的方案,那么返回空列表。
2.两种组合方案,只要存在一种产品的数量不同,那么方案认为是不同的.
3.每种产品型号价格不相同
4.1 <= 产品类型数量 <= 30
5.100 <= 产品价格<= 20000
6.100 <= 采购金额 <= 50000
package com.darling.boot.order.odt.odt24;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/**
* 硬件产品销售方案
* dfs
*/
public class My {
public static List<List<Integer>> res = new ArrayList<>();
public static int amount;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
amount = Integer.parseInt(str);
String line = sc.nextLine();
String s = line.replaceAll("\\[", "").replaceAll("]", "");
String[] strings = s.split(",");
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
List<Integer> tempList = new ArrayList<>();
dfs(array, 0, tempList, 0);
System.out.println(res);
}
public static void dfs(int[] array, int index, List<Integer> tempList, int sum) {
if (sum == amount) {
res.add(new ArrayList<>(tempList));
return;
}
for (int i = index; i < array.length; i++) {
int num = array[i];
if (sum + num > amount) {
break;
}
sum += num;
tempList.add(num);
//记得在这里传入的下标是i,不是index,千万不要搞错了
dfs(array, i, tempList, sum);
sum -= num;
tempList.remove(tempList.size() - 1);
}
}
}