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

2024-02-01

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

例如,如果 n = 4 且 k = 2,则output将会{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}.

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

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


递归是完成这项任务的朋友。

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

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]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

查找数组中长度为 k 的所有子集 的相关文章

随机推荐