Generate all unique combinations of Items

扶醉桌前 提交于 2021-02-07 08:21:34

问题


I trying to generate all possible unique combination of items.

Ex: item1, item2, item3

Combinations: 
   item1+item2+item3
   item1+item2
   item1+item3
   item2+item3
   item1
   item2
   item3

I am unable to get an idea on how to solve this?

for(int i=0;i<size;i++){
   for(int j=i+1;j<size;j++){
       System.out.println(list.item(i)+list.item(j));
   }
}

The above code certainly works for all unique combination of two elements. But not for 3 element pair and more..


回答1:


If you have N items, count from 1 to 2^N-1. Each number represents a combination, like so: if bit 0 (the least significant bit) is set, item1 is in the combination. If bit 1 is set, item2 is in the combination, and so on.

If you don't want 1-item combinations, start counting at 3, and ignore all the combinations that are a power of 2 (4, 8, 16, etc...).




回答2:


guava has that build in, if that's an option

 Set<Set<String>> result = Sets.powerSet(Sets.newHashSet("item1", "item2", "item3"));
    for(Set<String> token : result){
        System.out.println(token);
    }



回答3:


The following Java solution uses the bit approach proposed by zmbq :

  public static void allComb(int n) {
    BitSet bs = new BitSet();
    while (bs.length() <= n) {
      System.out.println(bs);
      //Inc by 1
      int pos = bs.nextClearBit(0);
      bs.flip(0, pos + 1);      
    }
  }


来源:https://stackoverflow.com/questions/21425346/generate-all-unique-combinations-of-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!