gpt4 book ai didi

arrays - 查找数组中长度为 k 的所有子集

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:14:46 24 4
gpt4 key购买 nike

给定一个包含 n 个元素的集合 {1,2,3,4,5...n},我们需要找到长度为 k 的所有子集。

例如,如果 n = 4 且 k = 2,输出 将是 {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}.

我什至不知道如何开始。我们不必使用 next_permutation 等内置库函数。

需要 C/C++ 或 Java 中的算法和实现。

最佳答案

递归是您完成此任务的 friend 。

对于每个元素 - “猜测”它是否在当前子集中,并使用猜测和您可以从中选择的较小超集递归调用。对"is"和“否”的猜测都这样做——将产生所有可能的子集。
在停止子句中很容易将自己限制在一定长度内。

Java代码:

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]]

关于arrays - 查找数组中长度为 k 的所有子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12548312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com