簡體   English   中英

字符串列表置換算法

[英]Permutation of a list of strings algorithm

我需要了解如何編寫置換算法的幫助。 (如果這甚至是排列,則它們必須是有序的並且使用相同的值)。

List<string> str = new List<string>{"a", "b", "c", "d"};

如何獲得此列表中可用的每個排列的列表? 例如。

  1. a, b, c, d
  2. ab, c, d
  3. ab, cd
  4. abc, d
  5. abcd
  6. a, bc, d
  7. a, bcd
  8. a, b, cd

由於某種原因,我找不到開始的模式。 當連接的字符串計數為X個字符時,我還希望能夠忽略排列。 因此,如果X在該列表中為4,則數字5將不存在,並且將有7個排列。

private List<string> permute(List<string> values, int maxPermutation)
{
     //alittle help on starting it would be great :)
}

我看了看這個 ,但他沒有保留命令。

這非常簡單:您可以在三個位置放置逗號或不放置任何內容。 共有8個組合,對應2 ^ 3個二進制數。

對於從0到7(含)之間的每個數字,產生一個二進制表示形式。 在每個二進制表示為1的位置放置逗號。 不要將逗號放在零處。

for (int m = 0 ; m != 8 ; m++) {
    string s = "a";
    if ((m & 1) != 0) s += ",";
    s += "b";
    if ((m & 2) != 0) s += ",";
    s += "c";
    if ((m & 4) != 0) s += ",";
    s += "d";
    Console.WriteLine(s);     
}

您可以采用遞歸方法:采用第一個字母,從第二個字母開始構建所有可能的組合(這是遞歸...),並在每個字母前加上第一個字母。 然后將前兩個字母放在一起,從第三個字母開始遞歸構建所有組合。 等等 ...

至於您的其他要求:如果要排除所有包含帶有X字母的字符串的“組合”,則在構造第一個字符串時只需跳過此數字。

上面的二進制方法是正確的,這實際上是一個分區問題(但不是“分區問題”),而不是排列問題。

http://en.wikipedia.org/wiki/Partition_of_a_set

請注意,因為分區的數量增長快於指數增長(e ^ e ^ n),因此對於大字符串而言,這確實會很慢。

請嘗試以下代碼。 我沒有測試過,但是我認為這是您想要的。

List<string> str = new List<string>{ "a", "h", "q", "z", "b", "d" };
List<List<string>> combinations = combine(str.OrderBy(s=>s).ToList());

List<List<string>> combine(List<string> items)
{
    List<List<string>> all = new List<List<string>>();

    // For each index item in the items array
    for(int i = 0; i < items.Length; i++)
    {
        // Create a new list of string
        List<string> newEntry = new List<string>();
        // Take first i items
        newEntry.AddRange(items.Take(i));
        // Concatenate the remaining items
        newEntry.Add(String.concat(items.Skip(i)));
        // Add these items to the main list
        all.Add(newEntry);

        // If this is not the last string in the list
        if(i + 1 < items.Length)
        {
            // Process sub-strings
            all.AddRange(combine(items.Skip(i + 1).ToList()));
        }
    }
    return all;
}

如果您需要生成組合(或排列或變體),那么Combinatorics是一個很棒的庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM