all possible combination of n sets

前端 未结 3 1123
终归单人心
终归单人心 2021-02-06 02:47

I have n Sets. each Set has different number of elements. I would like to write an algorithm which give me all possible combinations from the sets. for example: Lets say we have

3条回答
  •  借酒劲吻你
    2021-02-06 03:32

    Great solution by krilid, I modified it a bit to return a list of all combinations.

    @Test
    public void testMap() throws Exception {
        char[] one = new char[]{'a', 'b', 'c'};
        char[] two = new char[]{'d', 'e', 'f'};
        char[] three = new char[]{'g', 'h', 'i', 'j'};
        char[][] sets = new char[][]{one, two, three};
        List> collector = new ArrayList<>();
        ArrayList combo = new ArrayList<>();
        combinations(collector, sets, 0, combo);
        System.out.println(collector);
    }
    
    private void combinations(List> collector, char[][] sets, int n, ArrayList combo) {
        if (n == sets.length) {
            collector.add(new ArrayList<>(combo));
            return;
        }
        for (char c : sets[n]) {
            combo.add(c);
            combinations(collector, sets, n + 1, combo);
            combo.remove(combo.size() - 1);
        }
    }
    

提交回复
热议问题