【问题标题】:Select all combinations of elements选择所有元素组合
【发布时间】:2017-08-10 05:01:55
【问题描述】:

有一个MyOption元素列表:

class MyOption{
   List<Integer> listElements;
}

那么我有两个值allElementsselectedElements。第一个是listElements 的大小,第二个表示有多少列表项的值=0(其他为空)。 我必须得到 List&lt;MyOption&gt; ,其中每个 notnull 元素的组合。我知道总会有

( allElements! / (selectedElements! * (allElements - selectedElements)! ) 组合。

例如,allElements=3selectedElements=1 有: 3!/(1!*(3-1))! = 3 组合(listElements 的大小为 3,List&lt;MyOption&gt; 的大小也为 3):

0      null   null
null     0    null
null   null    0

第二个例子allElements=4selectedElements=2,有6种组合:

0      0     null  null
0     null    0    null
0     null   null   0
null   0      0    null
null   0     null   0
null  null    0     0

当我知道allElementsselectedElements 时,如何获得所有这些?

【问题讨论】:

  • 我相信这个SO Post 可以帮助你。您想考虑“排列”。

标签: java c++ algorithm


【解决方案1】:

在 c++ 中,您可以使用 std::next_permutation,类似:

std::vector<int> v {0, 0, 1, 1};

do {
    print(v);
} while (std::next_permutation(std::begin(v), std::end(v)));

Demo

【讨论】:

  • 或者只使用 Scala。那么就只有一行:List(0,0,null,null).permutations
【解决方案2】:

这是一种使用递归的可能解决方案。

private static void combinations(ArrayList<Integer> solution, int selectedElements, int start, ArrayList<List<Integer>> solutions) {
  if(selectedElements < 1) {
    solutions.add(new ArrayList<>(solution));
  } else {
    for(int i = start; i < solution.size() - selectedElements + 1; i++) {
      solution.set(i, 0);
      combinations(solution, selectedElements - 1, i+1, solutions);
      solution.set(i, null);
    }
  }
}
static List<List<Integer>> combinations(int allElements, int selectedElements) {
  ArrayList<List<Integer>> solutions = new ArrayList<>();
  ArrayList<Integer> solution = new ArrayList<>();
  for(int i = 0; i < allElements; i++) solution.add(null);
  combinations(solution, selectedElements, 0, solutions);
  return solutions;
}
public static void main(String[] args) {
  List<List<Integer>> solutions = combinations(4, 2);
  System.out.println(solutions);
}

【讨论】:

    【解决方案3】:

    有一个二项式系数的recursive definition 可以解决您的问题:

    public static long choose(long allElements, long selectedElements){
        if(allElements < selectedElements)
            return 0;
        if(selectedElements == 0 || selectedElements == allElements)
            return 1;
        return choose(allElements-1,selectedElements-1)+choose(allElements-1,selectedElements);
    }
    

    注意:这是一种易于理解的方法,适用于少量输入,还有更有效的实现方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 2011-12-14
      • 2015-09-28
      • 1970-01-01
      相关资源
      最近更新 更多