[英]How to code a backtracking method that returns all possible solutions in an Array?
I am student and I am stuck on this problem:我是学生,我被这个问题困住了:
The method gets an Array of Items and a certain amount of "money" as an Integer.该方法获取一个项目数组和一定数量的“钱”作为整数。 Every Item has a "prize" and a description.
每个项目都有一个“奖品”和一个描述。 Now I have to find all possible combinations of Items that could be bought with the money.
现在我必须找到可以用钱购买的所有可能的物品组合。 The supply of each Item is infinite and they can be bought several times.
每个物品的供应是无限的,可以多次购买。
I've managed to come up with a basic Algorithm that returns me the FIRST possible solution, but I have no idea how to get to the point where it returns ALL possible Solutions.我设法想出了一个基本算法,它返回给我第一个可能的解决方案,但我不知道如何到达返回所有可能解决方案的地步。
I'm thankful for any input!我很感谢任何输入!
An array of found solutions has a problem: an array is fixed-length in java.找到的解决方案的数组有一个问题:数组在java中是固定长度的。 Use a
List
instead, and pass that as parameter, to be filled.使用
List
代替,并将其作为参数传递,以进行填充。
Instead of a single solution:而不是单一的解决方案:
Solution s = search(param);
do:做:
List<Solution> solutions = new ArrayList<>();
search(param, solutions);
for (Solution s : solutions) {
System.out.println(s);
}
with和
void search (Param param, List<Solution> solutions) {
...
if (solved) {
solutions.add(new Solution(...));
return;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.