サイズnのリストのすべての可能なk個の組み合わせ

セオドアNarliyski:

私は、サイズNのリストから、サイズKのすべての可能な組み合わせを取得しようとしています

私は、「人間」のオブジェクトを取るリストを持っていると私は、リストオブジェクトで満たされる新しいのArrayListを作成しようとしています。リストのそれぞれは、「人間」のオブジェクトのさまざまな組み合わせになります。

番号の簡単な例は次のようになります:1,2,3からなるリストから私はこのようなそのルックスのArrayListを取得したい[[1,2], [1,3], [2,3]]、それはこのようになりますならば、私も気にしないだろう。[[1], [2], [3], [1,2], [1,3], [2,3]]

ここに私のコードは次のとおりです。

public void combination(List<Human> people, int k, ArrayList<List> result) {
    if (people.size() < k) {
        return;
    }
    if (k == 1) {
        for (Human hum : people) {
            List<Human> combinations = new ArrayList<Human>();
            combinations.add(hum);
            result.add(combinations);
        }
    }
    else if (people.size() == k) {
        List<Human> combinations = new ArrayList<Human>();
        for (Human hum : people) {
            combinations.add(hum);
        }
       result.add(combinations);
    }
    else if (people.size() > k) {
        for (int i = 0; i < people.size(); i++) {
            List<Human> combinations = new ArrayList<Human>();
            combinations.add(people.get(i));
            result.add(combinations);
            combination(people.subList(i + 1, people.size()), k - 1, result);
        }
    }
}

私は、参照として本サイト内の最後のメソッドを使用しています:https://hmkcode.com/calculate-find-all-possible-combinations-of-an-array-using-java/

現時点では私は私の新しいのArrayListに結果の正しい番号を取得するが、各リスト内の唯一の人間で構成されています。

私は非常に最後に問題の嘘を疑うelse if私は苦労再帰を理解しているからです。

どんな質問をするか、このための他の実装を提案すること自由に感じなさい。

アミールMB:

問題は、あなたが呼んでいるあなたのループの中でcombination初期設定がある場合は、[1,2,3,4,5]インスタンスの(唯一の連続サブリストに機能を、あなたは[のサブリストに関数を呼び出していない1,3,5 ])。

また、あなたがオーバーライドする必要があります覚えておいてequals、あなたの関数をHumanクラス。

    private void subsetsOf(List<Human> humans, int k, int index, Set<Human> tempSet, List<Set<Human>> finalSet) {
    if (tempSet.size() == k) {
        finalSet.add(new HashSet<>(tempSet));
        return;
    }

    if (index == humans.size())
        return;


    Human human = humans.get(index);

    tempSet.add(human);
    subsetsOf(humans, k, index+1, tempSet, finalSet);

    tempSet.remove(human);
    subsetsOf(humans, k, index+1, tempSet, finalSet);
}

public List<Set<Human>> combination(List<Human> humans, int k) {
    List<Set<Human>> result = new ArrayList<>();
    subsetsOf(humans, k, 0, new HashSet<Human>(), result);
    return result;
}

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=403882&siteId=1