是否有共同的模式来解决组合?

时间:2014-09-18 20:14:48

标签: algorithm combinations

假设您有两组,例如{a,b} xy {c,d,e},则返回所有组合(axyc,axyd,axye,bxyc,bxyd,bxye)。我知道有一个类似的,但我对答案Cartesian product of arbitrary sets in Java不满意,我的问题是,如果有一个共同的方法来解决它?

1 个答案:

答案 0 :(得分:2)

是的,有一种叫做“回溯”的方法,它是解决这类问题的常用模式。在这里查看:http://en.wikipedia.org/wiki/Backtracking 以下是代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
List<List<Character>> lists = new ArrayList<List<Character>>();
List<Character> l1 = new ArrayList<Character>();
l1.add('a'); l1.add('b');; l1.add('c');
List<Character> l2 = new ArrayList<Character>();
l2.add('#');
List<Character> l3 = new ArrayList<Character>();
l3.add('1'); l3.add('2');
lists.add(l1); lists.add(l2); lists.add(l3);

List<String> result = new ArrayList<String>();
GenerateCombinations(lists, result, 0, new StringBuilder());

System.out.println(result);
}


public static void GenerateCombinations(List<List<Character>> Lists, List<String> result, int    listIndex, StringBuilder combo)
{
    if(listIndex == Lists.size()) {
       result.add(combo.toString());       
} else {
    for(int i = 0; i < Lists.get(listIndex).size(); ++i)
    {
                //add new value 
        combo.append(Lists.get(listIndex).get(i));
                //get possible values in next list.
        GenerateCombinations(Lists, result, listIndex + 1, combo);
                //set back to old state.
        combo.deleteCharAt((combo.length() - 1));
    }
}

}