★★★] 设计一个函数,给定一个由整数组成的列表集合nums和一个整数target,其中列表中数值不重复,设计一个程序,找出列表集合中所有相加等于target的组合并输出在控制台上,要求输出的组合不能重复 例如:给定列表集合nums=[3,6,10,2,4,8,5,14,7]和target=9,输出(3, 6) (2, 7) (4, 5),其中(3, 6)和(6, 3)算一个组合用java
时间: 2023-06-06 07:08:19 浏览: 114
以下是Java代码实现:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombinationSum {
public static void main(String[] args) {
int[] nums = {3, 6, 10, 2, 4, 8, 5, 14, 7};
int target = 9;
List<List<Integer>> result = combinationSum(nums, target);
for (List<Integer> combination : result) {
System.out.println(combination);
}
}
public static List<List<Integer>> combinationSum(int[] nums, int target) {
Arrays.sort(nums); // 将数组从小到大排序方便后面去重
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, target, new ArrayList<>(), result, 0);
return result;
}
private static void backtrack(int[] nums, int target, List<Integer> combination, List<List<Integer>> result, int start) {
if (target == 0) { // 找到一个合法组合
result.add(new ArrayList<>(combination)); // 将组合存入结果中
return;
}
for (int i = start; i < nums.length && nums[i] <= target; i++) { // 遍历可用数字
if (i > start && nums[i] == nums[i - 1]) continue; // 防止重复
combination.add(nums[i]); // 添加当前数字
backtrack(nums, target - nums[i], combination, result, i + 1); // 递归
combination.remove(combination.size() - 1); // 回溯
}
}
}
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)