多个数组同顺序对比得到和所有原数组不同n位数的所有组合
时间: 2023-11-11 20:04:14 浏览: 79
要得到多个数组同顺序对比得到和所有原数组不同n位数的所有组合,可以使用递归的方法。首先对所有数组都进行排序,然后从第一个数组开始逐个选择数字,对于选择的每个数字,递归处理剩下的数组,并将得到的结果加上该数字构成新的结果。需要注意的是,由于每个数组都已经排好序,因此可以在比较时跳过相同的数字。以下是一个示例代码:
```
public static List<List<Integer>> getDifferentCombinations(int[][] nums, int n) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> current = new ArrayList<>();
getDifferentCombinationsHelper(nums, n, 0, 0, current, result);
return result;
}
public static void getDifferentCombinationsHelper(int[][] nums, int n, int index, int start, List<Integer> current, List<List<Integer>> result) {
if (current.size() == n) {
result.add(new ArrayList<>(current));
return;
}
if (index >= nums.length) {
return;
}
for (int i = start; i < nums[index].length; i++) {
if (i > start && nums[index][i] == nums[index][i - 1]) {
continue;
}
current.add(nums[index][i]);
getDifferentCombinationsHelper(nums, n, index + 1, i + 1, current, result);
current.remove(current.size() - 1);
}
}
```
其中,`nums` 表示所有数组,`n` 表示所需的不同数字的个数。调用 `getDifferentCombinations(nums, n)` 可以得到所有符合条件的组合。例如,对于数组 `{{1, 2, 2, 3}, {2, 2, 4}, {2, 3, 3}}`,如果需要得到所有由 3 个不同数字组成的组合,可以调用 `getDifferentCombinations(nums, 3)`。输出结果为:
```
[[1, 2, 4], [1, 3, 4], [2, 3, 4]]
```
即所有由 3 个不同数字组成的组合是 `[1, 2, 4]`、`[1, 3, 4]` 和 `[2, 3, 4]`。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)