在java中创建一个算法来查找所有可能的集群
Posted
技术标签:
【中文标题】在java中创建一个算法来查找所有可能的集群【英文标题】:Creating an algorithm to find all possible clusters in java 【发布时间】:2018-09-25 13:16:45 【问题描述】:我正在尝试找出如何将 [A0....An-1] 的所有可能集群找到 k 个非空集群,其中任何 n 在 java 中,例如:
A=[1,2,3,4] , n = 4 , k = 3
将返回这 3 个可能的集群选项:
[1][2][3,4]
[1][2,3][4]
[1,2][3][4]
对此的任何帮助将不胜感激!这些东西肯定不是我编程的强项,目前让我发疯!
【问题讨论】:
尝试先计算结果数。这可能会让你走上正轨。 【参考方案1】:您可以在此任务中使用递归。 代码
private static void getSubsets(List<Integer> superSet, int k, int idx, Set<Integer> current,List<Set<Integer>> solution)
//successful stop clause
if (current.size() == k)
solution.add(new HashSet<>(current));
return;
//unseccessful stop clause
if (idx == superSet.size()) return;
Integer x = superSet.get(idx);
current.add(x);
//"guess" x is in the subset
getSubsets(superSet, k, idx+1, current, solution);
current.remove(x);
//"guess" x is not in the subset
getSubsets(superSet, k, idx+1, current, solution);
public static List<Set<Integer>> getSubsets(List<Integer> superSet, int k)
List<Set<Integer>> res = new ArrayList<>();
getSubsets(superSet, k, 0, new HashSet<Integer>(), res);
return res;
功能
List<Integer> superSet = new ArrayList<>();
superSet.add(1);
superSet.add(2);
superSet.add(3);
superSet.add(4);
System.out.println(getSubsets(superSet,2));
输出
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
【讨论】:
【参考方案2】:如果你想用 c++ 实现,那么:
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
vector<int> v;
vector<vector<int> > result;
void subset(int arr[],int k,int n,int idx)
if(idx==n)
return;
if(k==1)
for(int i=idx;i<n;i++)
v.push_back(arr[i]);
result.push_back(v);
v.pop_back();
for(int j=idx;j<n;j++)
v.push_back(arr[j]);
subset(arr,k-1,n,j+1);
v.pop_back();
int main()
int arr[] = 1,2,3,4,5,6,7;
int k = 4;
int n =sizeof(arr)/sizeof(arr[0]);
subset(arr,k,n,0);
for(int i = 0;i<result.size();i++)
for(int j = 0;j<result[i].size();j++)
cout << result[i][j] << " ";
cout << endl;
【讨论】:
以上是关于在java中创建一个算法来查找所有可能的集群的主要内容,如果未能解决你的问题,请参考以下文章