2011-08-26 4 views
9

나는 List of elements (1, 2, 3)를 가지고 있으며 그 목록의 superset (powerset)을 가져야한다. 그래서 기본적으로 내가 보이는 목록의 목록 작성해야합니다 :목록의 가능한 모든 하위 집합 인쇄

{1} 
{2} 
{3} 
{1, 2} 
{1, 3} 
{2, 3} 
{1, 2, 3} 

최고의 무엇이를 구현하는 방법 (이 경우 단순> 효율이 목록은 거대한를하지 않습니다)? 가급적 자바에서는 가능하지만 모든 언어의 솔루션이 유용 할 것입니다.

+1

당신은 그 목록의 모든 부분 집합을 원한다. 재귀를 제안합니다. 그러나 30-40 개가 넘는 요소를 다루는 경우 보유한 1TB 이상의 거대한 데이터를 처리 할 수 ​​없습니다. 이 용도는 무엇입니까? –

+2

찾고있는이 데이터 구조를 Powerset (빈 세트가 포함 된 diffence)이라고합니다. 그것은 이미 SO에서 논의되었습니다. –

+0

Zenzen이 올바른 방향으로 나를 가리켜 주셔서 감사합니다 ... http://stackoverflow.com/questions/1670862/obtaining-powerset-of-a-set-in-java를 발견했습니다. – Steve

답변

31

사용 비트 마스크 :

1 = 001 = {1} 
2 = 010 = {2} 
3 = 011 = {1, 2} 
4 = 100 = {3} 
5 = 101 = {1, 3} 
6 = 110 = {2, 3} 
7 = 111 = {1, 2, 3} 

당신은 바이너리의 첫 번째 비트가 오른쪽 알고 :

int allMasks = (1 << N); 
for (int i = 1; i < allMasks; i++) 
{ 
    for (int j = 0; j < N; j++) 
     if ((i & (1 << j)) > 0) //The j-th element is used 
      System.out.print((j + 1) + " "); 

    System.out.println(); 
} 

여기에 모든 비트 마스크입니다. 페 타르 Minchev 솔루션을 기반으로

+0

이것은 매우 흥미 롭습니다 ... 당신은 분명히 제가 생각한 것보다 훨씬 더 똑똑합니다 - 이것에 대해 내 마음을 감쌀 수있는 시간을주세요 .... N은 원래 목록에있는 요소의 수입니까? 그리고 목록에있는 객체를 정수로 매핑합니까? – Steve

+0

@Steve - 예, 'N'은 'N = 3'위의 예에서 요소 수입니다. 이진수로 생각하십시오 - 요소가 사용되지 않으면 비트는 0이고 요소가 사용되면 비트가 1입니다. 예를 들어 이진수로 5 = 101입니다. 이것은 '1'과 '3'이 사용됨을 의미합니다. '= {1, 3}' –

+0

@ 스티브 - 내 편집 좀 봐. –

1
import java.io.*; 
import java.util.*; 
class subsets 
{ 
    static String list[]; 
    public static void process(int n) 
    { 
     int i,j,k; 
     String s=""; 
     displaySubset(s); 
     for(i=0;i<n;i++) 
     { 
      for(j=0;j<n-i;j++) 
      { 
       k=j+i; 
       for(int m=j;m<=k;m++) 
       { 
        s=s+m; 
       } 
       displaySubset(s); 
       s=""; 
      } 
     } 
    } 
    public static void displaySubset(String s) 
    { 
     String set=""; 
     for(int i=0;i<s.length();i++) 
     { 
      String m=""+s.charAt(i); 
      int num=Integer.parseInt(m); 
      if(i==s.length()-1) 
       set=set+list[num]; 
      else 
       set=set+list[num]+","; 
     } 
     set="{"+set+"}"; 
     System.out.println(set); 
    } 
    public static void main() 
    { 
     Scanner sc=new Scanner(System.in); 
     System.out.println("Input ur list"); 
     String slist=sc.nextLine(); 
     int len=slist.length(); 
     slist=slist.substring(1,len-1); 
     StringTokenizer st=new StringTokenizer(slist,","); 
     int n=st.countTokens(); 
     list=new String[n]; 
     for(int i=0;i<n;i++) 
     { 
      list[i]=st.nextToken(); 
     } 
     process(n); 
    } 
} 
+0

프로그램이 간단합니다. 먼저 1,2,3, ... n 자리 숫자의 각 목록의 마지막 숫자가 n 일 때까지 1-n 자리 숫자의 모든 가능한 조합을 얻으려고합니다. 그런 다음 각 조합을 사용하여 각 문자 (즉, 숫자)를 추출하고이 문자 (숫자)로 표시된 셀 색인에 저장된 하위 집합의 요소를 표시합니다. –

+0

코드 자체에 대한 설명을 주석에 추가하는 것이 더 낫습니다. 코드 만 사용한 답은 일반적으로 커뮤니티의 좋은 대답으로 간주되지 않습니다. –

0

자바 솔루션 - 답변이 문자열 목록에 집중되는 것을 내가 눈치 챘을

public static List<List<Integer>> getAllSubsets(List<Integer> input) { 
    int allMasks = 1 << input.size(); 
    List<List<Integer>> output = new ArrayList<List<Integer>>(); 
    for(int i=0;i<allMasks;i++) { 
     List<Integer> sub = new ArrayList<Integer>(); 
     for(int j=0;j<input.size();j++) { 
      if((i & (1 << j)) > 0) { 
       sub.add(input.get(j)); 
      } 
     } 
     output.add(sub); 
    } 

    return output; 
} 
0

. 결과적으로보다 일반적인 답변을 공유하기로했습니다. 도움이 될 수 있기를 바랍니다. (Soultion은 내가 찾은 또 다른 솔루션을 기반으로, 나는 일반적인 algorithem에 결합.)

/** 
* metod returns all the sublists of a given list 
* the method assumes all object are different 
* no matter the type of the list (generics) 
* @param list the list to return all the sublist of 
* @param <T> 
* @return list of the different sublists that can be made from the list object 
*/ 
public static <T> List<List<T>>getAllSubLists(List<T>list) 
{ 
    List<T>subList; 
    List<List<T>>res = new ArrayList<>(); 
    List<List<Integer>> indexes = allSubListIndexes(list.size()); 
    for(List<Integer> subListIndexes:indexes) 
    { 
     subList=new ArrayList<>(); 
     for(int index:subListIndexes) 
      subList.add(list.get(index)); 
     res.add(subList); 
    } 
    return res; 
} 
/** 
* method returns list of list of integers representing the indexes of all the sublists in a N size list 
* @param n the size of the list 
* @return list of list of integers of indexes of the sublist 
*/ 
public static List<List<Integer>> allSubListIndexes(int n) { 
    List<List<Integer>> res = new ArrayList<>(); 
    int allMasks = (1 << n); 
    for (int i = 1; i < allMasks; i++) 
    { 
     res.add(new ArrayList<>()); 
     for (int j = 0; j < n; j++) 
      if ((i & (1 << j)) > 0) 
       res.get(i-1).add(j); 

    } 
    return res; 
} 
관련 문제