All possible combinations of an array

前端 未结 7 649
甜味超标
甜味超标 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:29

    import java.util.ArrayList;
    import java.util.List;
    public class AllPossibleCombinations {
    
    public static void main(String[] args) {
        String[] a={"ted", "williams", "golden"};           
        List> list = new AllPossibleElementCombinations().getAllCombinations(Arrays.asList(a));
        for (List arr:list) {
            for(String s:arr){
                System.out.print(s);
            }
            System.out.println();
        }
    }
    
    public List> getAllCombinations(List elements) {
        List> combinationList = new ArrayList>();
        for ( long i = 1; i < Math.pow(2, elements.size()); i++ ) {
            List list = new ArrayList();
            for ( int j = 0; j < elements.size(); j++ ) {
                if ( (i & (long) Math.pow(2, j)) > 0 ) {
                    list.add(elements.get(j));
                }
            }
            combinationList.add(list);
        }
        return combinationList;
    }
    
    }
    

    output:

    ted

    williams

    tedwilliams

    golden

    tedgolden

    williamsgolden

    tedwilliamsgolden

提交回复
热议问题