酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Java 实现:给定总价,列出不同单价商品的所有符合组合!

以下是一个简单的 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); } } ``` 这个程序使用递归的方式来找出所有可能的商品组合。对于较大的商品数量和总价,可能会产生大量的组合,导致性能问题。在实际应用中,可能需要根据具体情况进行优化或采用其他算法。 ######[AI写代码神器 | 432点数解答 | 2024-09-03 11:49:30]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]