How to get 2D array possible combinations

前端 未结 5 1971
爱一瞬间的悲伤
爱一瞬间的悲伤 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:44

    Should be straight forward to do with recursion.

    Let me rephrase a bit, so the terminology is less confusing.

    We will call String[] as Token List, which is a list of Tokens

    Now you have a List of Token List, you want to get one Token from each Token List available, and find out all combination.

    What you need to do is, given a list of TokenList

    • If the List is having only one TokenList, the content of the Token List itself is all combinations
    • Else, make a sub-list by excluding the first Token List, and find out all combinations of that sub list. When you have the combinations, the answer is simply loop through your first token list, and generate all combinations using each token in the token list, and the result combinations.

    I am only giving a psuedo code:

    List allCombinations(List listOfTokenList) {
      if (length of strings == 1) {
        return strings[0];
      }
    
    
      List subListCombinations 
          = allCombination(listOfTokenList.subList(1));  // sublist from index 1 to the end
    
    
      List result;
      for each (token in listOfTokenList[0]) {
        for each (s in subListCombination) {
          result.add(token + s);
        }
      }
      return result;
    }
    

提交回复
热议问题