How to get 2D array possible combinations

前端 未结 5 2086
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 20:18

I have the following 2D array:

String[M][]

String[0]
   \"1\",\"2\",\"3\"

String[1]
   \"A\", \"B\"
   .
   .
   .
String[M-1]
   \"!\"

A

5条回答
  •  青春惊慌失措
    2020-12-17 20:51

    This problem has a very nice recursive structure to it (which also means it could explode in memory, the correct way should be using iterators such as the other answer, but this solution looks nicer imo and we can prove correctness inductively because of the recursive nature). A combination consists of an element from the first list attached to all possible combinations formed from the remaining (n-1) lists. The recursive work is done in AllCombinationsHelper, but you invoke AllCombinations. Note to test for empty lists and more extensively.

    public static List AllCombinations(List> aList) {
        if(aList.size() == 0) { return new ArrayList(); }
        List myFirstSubList = aList.remove(0);
        List myStrings = new ArrayList();
        for(Character c : myFirstSubList) {
            myStrings.add(c.toString());
        }
    
        return AllCombinationsHelper(aList, myStrings);
    }
    
    public static List AllCombinationsHelper(List> aList, 
                                                     List aCollection) {
        if(aList.size() == 0) { return aCollection; }
        List myFirstList = aList.remove(0);
        List myReturnSet = new ArrayList();
    
        for(String s : aCollection) {
            for(Character c : myFirstList) {
                myReturnSet.add(c + s);
            }
        }
    
        return AllCombinationsHelper(aList, myReturnSet);
    }
    

提交回复
热议问题