java - 如何使用来自多个不同矩阵的值找到子序列?
问题描述
我有三个 2*2 矩阵。我需要从中找到所有可能的序列。但条件是我不能从每个矩阵中获取多个值。假设:matrix1[][]= {1,2,3,4} matrix2[][]= {5,6,7,8} matrxi3[][]= {9,10,11,12} 子集可以是(1,5,9),(4,5,11),(3,7,12)......等等。但不是 (1,2,7) 或 (4,10,12)。条件是,值不能来自同一个矩阵。我尝试将 2*2 矩阵的值排列在一维数组中,然后尝试应用递归解决方案,但找不到合适的条件。这是从给定数组中查找常用子集的代码:
class Combination {
static void combinationUtil(int arr[], int data[], int start,
int end, int index, int r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
for (int j=0; j<r; j++)
System.out.print(data[j]+" ");
System.out.println("");
return;
}
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
static void printCombination(int arr[], int n, int r)
{
int data[]=new int[r];
combinationUtil(arr, data, 0, n-1, 0, r);
}
/*Driver function to check for above function*/
public static void main (String[] args) {
int arr[] = {1,2,3,4,5,6,7,8,9,10,11,12};
int r = 3;
int n = arr.length;
printCombination(arr, n, r);
}
}
解决方案
您只需要遍历所有三个数组(矩阵),例如使用嵌套循环。这个解决方案怎么样:
public class Easy {
public static void main(String[] argg) {
int[] m1 = new int[]{1,2,3,4};
int[] m2 = new int[]{5,6,7,8};
int[] m3 = new int[]{9,10,11,12};
printCombination(m1, m2, m3);
}
public static void printCombination(int[] first, int[] second, int[] third) {
for (int f : first) {
for (int s : second) {
for (int t : third) {
System.out.println("combination: " + f + ", " + s + ", " + t);
}
}
}
}
}
推荐阅读
- javascript - How to allow async programmatic copy-to-clipboard functionality in FireFox
- python - 如何在 Django 中使用 CBV 中的表单集?
- react-admin - 将 ReferenceArrayInput 与非平面数组一起使用
- python - 导入 Boost Python 模块时出错 (function_impl_base9max_arityEv)
- c++ - 使用 occi 库将 c++ 程序与 Oracle 连接
- android - 布局问题并帮助我解决在所有设备中扩展的问题
- sql-server - 在 ubuntu 上配置 MSSQL Server - 无法打开或读取持久注册表:\SystemRoot\security.hiv
- rrdtool - 如何创建具有特定时间的rrd文件?
- javascript - 无法创建 HTML
- authentication - 如何实现跨域单点登录