以下是一个简单的 Java 程序示例,用于解决给定一组不同单价的商品和总价,列出所有符合的商品组合的问题: ```java import java.util.ArrayList; import java.util.List; public class CombinationsOfProducts { public static void main(String[] args) { double[] prices = {10.5, 20.0, 15.5, 8.0, 12.5}; double totalPrice = 50.0; findCombinations(prices, totalPrice); } public static void findCombinations(double[] prices, double totalPrice) { List<List<Double>> combinations = new ArrayList<>(); findCombinationsHelper(prices, 0, new ArrayList<>(), totalPrice, combinations); for (List<Double> combination : combinations) { System.out.println(combination); } } public static void findCombinationsHelper(double[] prices, int index, List<Double> currentCombination, double remainingPrice, List<List<Double>> combinations) { if (remainingPrice == 0) { combinations.add(new ArrayList<>(currentCombination)); return; } if (remainingPrice < 0 || index == prices.length) { return; } currentCombination.add(prices[index]); findCombinationsHelper(prices, index + 1, currentCombination, remainingPrice - prices[index], combinations); currentCombination.remove(currentCombination.size() - 1); findCombinationsHelper(prices, index + 1, currentCombination, remainingPrice, combinations); } } ``` 这个程序使用递归的方式来找出所有可能的商品组合。对于较大的商品数量和总价,可能会产生大量的组合,导致性能问题。在实际应用中,可能需要根据具体情况进行优化或采用其他算法。 [2024-09-03 11:49:30 | AI写代码神器 | 432点数解答]