2017-08-05 53 views
-2

考慮字符數組characterArray = {A,B,C,d}。我想創建一個包含所有可能的元素組合的列表作爲一個Set。例如生成元素的所有可能的組合,從字符數組 - 使用集合框架(List和Set)

Set 1 ={} 
Set 2 = {a} 
Set 3 = {b} 
Set 4 = {c} 
Set 5 = {a,b} 
Set 6 ={a,c} 
...... 
...... 
Set N = {a,b,c,d} 

在生成上述所有可能的組合後。我想將所有上面生成的集合添加到列表(List)中。

下面是示例代碼編寫

public class CreateSets { 

    char a[] = { 'a', 'b', 'c', 'd' }; 
    List<HashSet> setList = new ArrayList<HashSet>(); 

    public void createSubsets() { 
     for (int i = 0; i < a.length; i++) { 
      HashSet temp = new HashSet(); 
      for (int j = i; j < a.length; j++) { 
       temp.add(a[j]); 
      } 
      setList.add(temp); 
     } 

    } 
    public static void main(String[] args) { 
     CreateSets cr = new CreateSets(); 
     cr.createSubsets(); 
     System.out.println(cr.setList); 
    } 

} 
+2

您已經編寫任何代碼? – SilverNak

+1

的【計算所有的一組數字的子集(https://stackoverflow.com/questions/4640034/calculating-all-of-the-subsets-of-a-set-of-numbers) – Dukeling

+0

可能的複製@SilverNak。用代碼更新 – Raghu

回答

1
private List<HashSet<Character>> createSubsets(char[] a) { 
     List<HashSet<Character>> tempListList = new ArrayList<HashSet<Character>>(); 
     if (a.length == 0) { 
      HashSet<Character> temp = new HashSet<Character>(); 
      //temp.add(' '); 
      tempListList.add(temp); 
      return tempListList; 
     } 
     char tempChar = a[a.length-1]; 
     List<HashSet<Character>> setList = createSubsets(Arrays.copyOf(a, a.length-1)); 
     for (HashSet<Character> charSet : setList) { 
      HashSet<Character> tempSet = new HashSet<>(charSet); 
      tempSet.add(tempChar); 
      tempListList.add(tempSet); 
     } 
     setList.addAll(tempListList); 
     return setList; 
    }