简体   繁体   English

如何编写返回数组中所有可能解决方案的回溯方法?

[英]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.

相关问题 数独 - 递归回溯可能 - 解决方案 - 计数器 - Sudoku - Recursive Backtracking possible-solutions-counter 如何将解决方案从递归方法调用传递到调用方法? (回溯算法) - How do I pass solutions from recursive method call to calling method? (backtracking algorithm) 如何修改此递归回溯算法(NQueens)以查找所有解决方案,而不仅仅是一个? - How can I modify this recursive backtracking algorithm (NQueens) to find all solutions instead of just one? 获取数独可能的解决方法 - Getting sudoku possible solutions Method 为什么回溯无法生成所有可能的组合? - Why is backtracking unable to generate all possible combinations? 如何创建一个方法接受一个数组并找到一个数字的所有出现并返回它发生的所有索引的新数组 - How to create a method takes in an array and finds all occurances of a number and returns a new array of all the indexs that it occurs A *(A Star)算法输出所有可能的解决方案 - A* (A Star) Algorithm outputting all possible solutions 回溯所有选择酒瓶方式的解决方案 - Backtracking solution of all possible ways of choosing wine bottle java-将数组的所有可能组合合并为一个方法 - java - All possible combinations of an array into one method 是否有一种方法会为n选择k返回所有可能的组合? - Is there a method returns all possible combinations for n choose k?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM