All possible combinations of an array

前端 未结 7 626
甜味超标
甜味超标 2020-11-30 05:51

I have an string array

{\"ted\", \"williams\", \"golden\", \"voice\", \"radio\"}

and I want all possible combinations of these keywords in

7条回答
  •  遥遥无期
    2020-11-30 06:36

    EDIT: As FearUs pointed out, a better solution is to use Guava's Sets.powerset(Set set).

    EDIT 2: Updated links.


    Quick and dirty translation of this solution:

    public static void main(String[] args) {
    
        List> powerSet = new LinkedList>();
    
        for (int i = 1; i <= args.length; i++)
            powerSet.addAll(combination(Arrays.asList(args), i));
    
        System.out.println(powerSet);
    }
    
    public static  List> combination(List values, int size) {
    
        if (0 == size) {
            return Collections.singletonList(Collections. emptyList());
        }
    
        if (values.isEmpty()) {
            return Collections.emptyList();
        }
    
        List> combination = new LinkedList>();
    
        T actual = values.iterator().next();
    
        List subSet = new LinkedList(values);
        subSet.remove(actual);
    
        List> subSetCombination = combination(subSet, size - 1);
    
        for (List set : subSetCombination) {
            List newSet = new LinkedList(set);
            newSet.add(0, actual);
            combination.add(newSet);
        }
    
        combination.addAll(combination(subSet, size));
    
        return combination;
    }
    

    Test:

    $ java PowerSet ted williams golden
    [[ted], [williams], [golden], [ted, williams], [ted, golden], [williams, golden], [ted, williams, golden]]
    $
    

提交回复
热议问题