递归打印ArrayList <arraylist <string >>的所有可能组合

时间:2018-10-10 15:54:32

标签: java recursion

我正在尝试练习递归,但是对于我一生来说,我不知道该怎么做。假设我在一个数组列表中有3个或更多的数组列表,我想使用递归打印所有可能的组合。我该怎么办?

这是我到目前为止所拥有的

public static void main(String[] args)
{
    ArrayList<ArrayList<String>> combList = new ArrayList<ArrayList<String>>();
    ArrayList<String> fruitList = new ArrayList<String>();
    ArrayList<String> lNameList = new ArrayList<String>();
    ArrayList<String> locationList = new ArrayList<String>();

    fruitList.add("Apple");
    fruitList.add("Orange");
    fruitList.add("Grape");
    combList.add(fruitList);

    colorList.add("Red");
    colorList.add("Green");
    colorList.add("Blue");
    combList.add(colorList);

    numberList.add("One");
    numberList.add("Two");
    numberList.add("Three");
    combList.add(numberList);

    combinations(combList, 0, 0, "");
}

public static void combinations(ArrayList<ArrayList<String>> combList, int listIndex, int itemIndex, String result)
{
    // Am I at the bottom of the y-axis?
    if(listIndex < combList.size())
    {
        //Am I at the bottom of the x-axis?
        if(itemIndex < combList.size())
        {
            ArrayList<String> curList = combList.get(listIndex);
            StringBuilder sb = new StringBuilder();
            sb.append(result).append(curList.get(itemIndex)).append(" ");
            combinations(combList, listIndex + 1, itemIndex, sb.toString());
            combinations(combList, listIndex, itemIndex + 1, result);
        }
        return;
    }
    System.out.println(result);
    return;
}

我正在尝试将其打印出来

Apple Red One
Apple Red Two
Apple Red Three
Apple Green One
Apple Green Two
Apple Green Three
Apple Blue One
Apple Blue Two
Apple Blue Three
Orange Red One
Orange Red Two
Orange Red Three
Orange Green One
. . . 
Grape Blue Three

4 个答案:

答案 0 :(得分:1)

主要问题是,当您移至下一个列表时

combinations(combList, listIndex + 1, itemIndex, sb.toString());

您允许对其进行迭代,但只能从当前itemIndex所持有的位置进行迭代。这样可以防止您迭代其最初的元素。解决方案将使用

combinations(combList, listIndex + 1, 0, sb.toString());
//                                    ^--start iterating from first list item

另一个问题是您打电话给curList.get(itemIndex),但之前测试过

if(itemIndex < combList.size()){ ... }

如您所见,您正在比较内部列表中的索引与外部列表的大小。这仅在两个大小相同的情况下才有效-如果每个内部列表的元素数量与内部列表的数量相同。您需要的是

if(itemIndex < combList.get(listIndex).size()){ ... }

下一个可能的问题是您没有处理空的内部列表。假设您有[[a1,a2],[],[c1,c2]]。由于第二个内部列表中没有元素,因此您的代码将不允许您移至下一个内部列表,因为combinations(combList, listIndex, itemIndex + 1, result);if(itemIndex < combList.get(listIndex).size())中被调用。要处理这种情况,您可以添加else这样的情况,例如

if(itemIndex < combList.get(listIndex).size())
{
    //...
} else if (combList.get(listIndex).isEmpty()){
    combinations(combList, listIndex + 1, 0, result);
}

因此您的方法应类似于: Demo

public static void main(String[] args) {

    List<List<String>> combList = new ArrayList<>();
    combList.add(Arrays.asList("a1", "a2", "a3"));
    combList.add(Arrays.asList("b1", "b2"));
    combList.add(Arrays.asList());
    combList.add(Arrays.asList("c1", "c2", "c3"));

    combinations(combList, 0, 0, "");
}

public static void combinations(List<List<String>> combList, int listIndex, int itemIndex, String result)
{
    // Am I at the bottom of the y-axis?
    if(listIndex < combList.size())
    {
        //Am I at the bottom of the x-axis?
        if(itemIndex < combList.get(listIndex).size())
        {
            List<String> curList = combList.get(listIndex);
            StringBuilder sb = new StringBuilder();
            sb.append(result).append(curList.get(itemIndex)).append(" ");
            combinations(combList, listIndex + 1, 0, sb.toString());
            combinations(combList, listIndex, itemIndex + 1, result);
        }else if (combList.get(listIndex).isEmpty()){
            combinations(combList, listIndex + 1, 0, result);
        }
        return;
    }
    System.out.println(result);
    //return; - redundant as last instruction of method
}

输出:

a1 b1 c1 
a1 b1 c2 
a1 b1 c3 
a1 b2 c1 
a1 b2 c2 
a1 b2 c3 
a2 b1 c1 
a2 b1 c2 
a2 b1 c3 
a2 b2 c1 
a2 b2 c2 
a2 b2 c3 
a3 b1 c1 
a3 b1 c2 
a3 b1 c3 
a3 b2 c1 
a3 b2 c2 
a3 b2 c3 

答案 1 :(得分:0)

我们需要递归处理另一种情况

<a href='https://www.acadoo.de/de-ghostwriter-bachelorarbeit.html'>Ghostwriter Bachelorarbeit</a>
<script type='text/javascript' src='https://embedmaps.com/google-maps-authorization/script.js?id=274228f8880db3e0b587b128af8f2a5a49d26d62'></script>

输出:

<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyDvV9lr4YTbExSlhYI2e26aTEaoY2peUwE'></script>
<div style='overflow:hidden;height:280px;width:1382px;'>
  <div id='gmap_canvas' style='height:280px;width:1382px;'></div>
  <style>
    #gmap_canvas img {
      max-width: none!important;
      background: none!important
    }
  </style>
</div>
<script type='text/javascript'>
  function init_map() {
    var myOptions = {
      zoom: 14,
      center: new google.maps.LatLng(47.4464864, 9.526921600000037),
      mapTypeId: google.maps.MapTypeId.HYBRID
    };
    map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);
    marker = new google.maps.Marker({
      map: map,
      position: new google.maps.LatLng(47.4464864, 9.526921600000037)
    });
    infowindow = new google.maps.InfoWindow({
      content: '<strong>Klinik Am Rosenberg</strong><br>Hasenbühlstrasse 11<br>9410 Heiden<br>'
    });
    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map, marker);
    });
    infowindow.open(map, marker);
  }
  google.maps.event.addDomListener(window, 'load', init_map);
</script>

答案 2 :(得分:0)

我的代码。解决方案中的顺序颠倒了,但是如果这很重要,那么应该很容易解决。同样,递归方法返回需要转换为字符串的列表列表。

import java.util.ArrayList;
import java.util.Arrays;

public class Combinations {
    public static void main(String[] args) {
        ArrayList<ArrayList<String>> combList = new ArrayList<ArrayList<String>>();
        ArrayList<String> fruitList = new ArrayList<String>();
        ArrayList<String> colorList = new ArrayList<String>();
        ArrayList<String> numberList = new ArrayList<String>();

        fruitList.add("Apple");
        fruitList.add("Orange");
        fruitList.add("Grape");
        combList.add(fruitList);

        colorList.add("Red");
        colorList.add("Green");
        colorList.add("Blue");
        combList.add(colorList);

        numberList.add("One");
        numberList.add("Two");
        numberList.add("Three");
        combList.add(numberList);

        ArrayList<ArrayList<String>> combs = combinations(combList);
        for (ArrayList<String> al: combs) {
            System.out.println(String.join(" ", al));
        }
    }

    public static ArrayList<ArrayList<String>> combinations(ArrayList<ArrayList<String>> combList) {
        if (combList.size() == 0) {
            ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
            ret.add(new ArrayList<String>());
            return ret;
        } else {
            ArrayList<String> levelList = combList.remove(0);
            ArrayList<ArrayList<String>> subAnswer = combinations(combList);
            ArrayList<ArrayList<String>> newList = new ArrayList<ArrayList<String>>();
            for (ArrayList<String> solList : subAnswer) {
                for (String s: levelList) {
                    ArrayList<String> newComb = new ArrayList<String>(solList);
                    newComb.add(s);
                    newList.add(newComb);
                }
            }
            return newList;
        }
    }
}

答案 3 :(得分:0)

import java.util.Arrays;
import java.util.List;

public class PrintAllCombinations {

public void printCombination(List<List<String>> a, int n, String b) {
    if (n == a.size()) {
        System.out.println(b);
        return;
    }
    for (int j = 0; j < a.get(n).size(); j++)
        printCombination(a, n + 1, b + a.get(n).get(j));
}

public static void main(String[] args) {
    PrintAllCombinations printAllCombinations = new PrintAllCombinations();
    List<List<String>> a = Arrays.asList(Arrays.asList("10 ", "20 ", "30 "), Arrays.asList("40 ", "50 ", "60 "), Arrays.asList("70 ", "80 ", "90 "));
    printAllCombinations.printCombination(a, 0, "");
 }
}

输出:

  • 10 40 70
  • 10 40 80
  • 10 40 90
  • 10 50 70
  • 10 50 80
  • 10 50 90
  • 10 60 70
  • 10 60 80
  • 10 60 90
  • 20 40 70
  • 20 40 80
  • 20 40 90
  • 20 50 70
  • 20 50 80
  • 20 50 90
  • 20 60 70
  • 20 60 80
  • 20 60 90
  • 30 40 70
  • 30 40 80
  • 30 40 90
  • 30 50 70
  • 30 50 80
  • 30 50 90
  • 30 60 70
  • 30 60 80
  • 30 60 90
相关问题