2013-10-05 57 views
1

我正在編寫一個程序來列出一個字符串的所有子集。我的程序(下面給出)按此順序列出「abcd」的子集:這些子集的順序是什麼?

'' 'd' 'c' 'cd' 'b' 'bd' 'bc' 'bcd' 'a' 'ad' 'ac' 'acd' 'ab' 'abd' 'abc' 'abcd' 

這是正確的。然而,對照品溶液列出他們在這個順序:

'' 'a' 'b' 'ab' 'c' 'ac' 'bc' 'abc' 'd' 'ad' 'bd' 'abd' 'cd' 'acd' 'bcd' 'abcd' 

我的問題是:這是什麼順序的名字嗎?

供參考,這是我的計劃:

import java.util.ArrayList; 
import java.util.Collections; 

/** 
    This class generates subsets of a string. 
*/ 
public class SubsetGenerator 
{ 
    public static ArrayList<String> getSubsets(String word) 
    { 
     ArrayList<String> result = new ArrayList<String>(); 
     //fill out 
     //result.add(""); 
     if(word.length() == 0) 
     { 

      result.add(""); 
     } 

    else 
    { 
     String notFirst = word.substring(1); 
     ArrayList<String> smaller = getSubsets(notFirst); 
     //System.out.println(smaller); 
     char first = word.charAt(0); 

     result.addAll(smaller); 

     for(String i: smaller) 
     { 
      result.add(first+i); 
     } 
    } 


    //simpleSubsets = getSubsets(simple+word.charAt(0)); 

    // Form a simpler word by removing the first character 
    // fill out 

    // Generate all subsets of the simpler word 
    // fill out 

    // Add the removed character to the front of 
    // each subset of the simpler word, and 
    // also include the word without the removed character 
    // fill out 

    // Return all subsets 
    return result; 
    } 
} 
+0

特定的順序是什麼?以及你的結果指的是什麼?爲什麼你得到的正確輸出是正確的? –

回答

1

,他們正在生產是,如果你在二進制計數關閉,轉換數字0和1的你會得到的順序排序, b,c和d:

d c b a | set 
--------+---- 
0 0 0 0 | {} 
0 0 0 1 | {a} 
0 0 1 0 | {b} 
0 0 1 1 | {a, b} 
0 1 0 0 | {c} 
0 1 0 1 | {a, c} 
0 1 1 0 | {b, c} 
0 1 1 1 | {a, b, c} 
1 0 0 0 | {d} 
1 0 0 1 | {a, d} 
1 0 1 0 | {b, d} 
1 0 1 1 | {a, b, d} 
1 1 0 0 | {c, d} 
1 1 0 1 | {a, c, d} 
1 1 1 0 | {b, c, d} 
1 1 1 1 | {a, b, c, d} 

希望這有助於!

+0

我修正了我的程序,但我仍然無法圍繞這個二進制排序如何工作。我沒有看到0和1的模式。你能否詳細解釋一下?我對這種訂購非常陌生 –

+0

Nevermind我只記得我在離散數學課上學到了這些。非常感謝。 –

+0

「二元排序就像十進制排序,如果你缺少八個手指,那真的是。」 - 湯姆萊勒 –