質問

文字の可変リストを含む、長さが x 文字と y 文字の間の文字列の可能なすべての順列のリストを生成するにはどうすればよいでしょうか。

どの言語でも機能しますが、移植可能である必要があります。

役に立ちましたか?

解決

これを行うにはいくつかの方法があります。一般的な方法では、再帰、メモ化、または動的プログラミングが使用されます。基本的な考え方は、長さ 1 のすべての文字列のリストを生成し、各反復で、最後の反復で生成されたすべての文字列に対して、その文字列を文字列内の各文字と個別に連結して追加するというものです。(以下のコードの変数インデックスは、最後の反復と次の反復の開始を追跡します)

いくつかの疑似コード:

list = originalString.split('')
index = (0,0)
list = [""]
for iteration n in 1 to y:
  index = (index[1], len(list))
  for string s in list.subset(index[0] to end):
    for character c in originalString:
      list.add(s + c)

次に、長さが x 未満のすべての文字列を削除する必要があります。これらは、リストの最初の (x-1) * len(originalString) エントリになります。

他のヒント

バックトラッキングを使った方が良い

#include <stdio.h>
#include <string.h>

void swap(char *a, char *b) {
    char temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

void print(char *a, int i, int n) {
    int j;
    if(i == n) {
        printf("%s\n", a);
    } else {
        for(j = i; j <= n; j++) {
            swap(a + i, a + j);
            print(a, i + 1, n);
            swap(a + i, a + j);
        }
    }
}

int main(void) {
    char a[100];
    gets(a);
    print(a, 0, strlen(a) - 1);
    return 0;
}

たくさんの文字列が得られることは確かです...

\sum_{i=x}^y{\frac{r!}{{(r-i)}!}} http://www.codecogs.com/eq.latex?%5Csum_%7Bi=x%7D%5Ey% 20%7B%20%5Cfrac%7Br!%7D%7B%7B(r-i)%7D!%7D%20%7D
ここで、x と y は定義方法、r は選択する文字の数です。私の理解が正しければの話ですが。これらは必要に応じて確実に生成する必要があり、パワーセットを生成してから文字列の長さをフィルタリングするなどという雑なことはしないでください。

以下はこれらを生成する最適な方法ではありませんが、それでも興味深い余談です。

Knuth (volume 4、fascicle 2、7.2.1.3) は、(s,t) 組み合わせは、一度に s+1 個の物を t ずつ繰り返して取得するのと同等であると述べています。(s,t) 組み合わせは、次の方法で使用される表記法です。以下に等しいクヌート {t \choose {s+t} http://www.codecogs.com/eq.latex?%7Bt%20%5Cchoose%20%7Bs+t%7D%7D. 。これは、まず各 (s,t) の組み合わせをバイナリ形式 (つまり、長さ (s+t)) で生成し、各 1 の左側にある 0 の数をカウントすることでわかります。

10001000011101 --> は順列になります:{0、3、4、4、4、1}

Knuth による非再帰的解決策、Python の例:

def nextPermutation(perm):
    k0 = None
    for i in range(len(perm)-1):
        if perm[i]<perm[i+1]:
            k0=i
    if k0 == None:
        return None

    l0 = k0+1
    for i in range(k0+1, len(perm)):
        if perm[k0] < perm[i]:
            l0 = i

    perm[k0], perm[l0] = perm[l0], perm[k0]
    perm[k0+1:] = reversed(perm[k0+1:])
    return perm

perm=list("12345")
while perm:
    print perm
    perm = nextPermutation(perm)

「」を見てください。セットのサブセットを効率的に列挙するこれは、長さ x から y までの N 文字のすべてのサブセットを迅速に生成するという、必要なことの一部を実行するアルゴリズムについて説明しています。C での実装が含まれています。

サブセットごとに、すべての順列を生成する必要があります。たとえば、「abcde」から 3 文字が必要な場合、このアルゴリズムでは「abc」、「abd」、「abe」...が得られます。ただし、「acb」、「bac」、「bca」などを取得するには、それぞれを並べ替える必要があります。

いくつかの動作する Java コードは以下に基づいています サープの答え:

public class permute {

    static void permute(int level, String permuted,
                    boolean used[], String original) {
        int length = original.length();
        if (level == length) {
            System.out.println(permuted);
        } else {
            for (int i = 0; i < length; i++) {
                if (!used[i]) {
                    used[i] = true;
                    permute(level + 1, permuted + original.charAt(i),
                       used, original);
                    used[i] = false;
                }
            }
        }
    }

    public static void main(String[] args) {
        String s = "hello";
        boolean used[] = {false, false, false, false, false};
        permute(0, "", used, s);
    }
}

C# での簡単な解決策を次に示します。

指定された文字列の個別の順列のみを生成します。

    static public IEnumerable<string> permute(string word)
    {
        if (word.Length > 1)
        {

            char character = word[0];
            foreach (string subPermute in permute(word.Substring(1)))
            {

                for (int index = 0; index <= subPermute.Length; index++)
                {
                    string pre = subPermute.Substring(0, index);
                    string post = subPermute.Substring(index);

                    if (post.Contains(character))
                            continue;                       

                    yield return pre + character + post;
                }

            }
        }
        else
        {
            yield return word;
        }
    }

ここには良い答えがたくさんあります。また、C++ での非常に簡単な再帰的ソリューションも提案します。

#include <string>
#include <iostream>

template<typename Consume>
void permutations(std::string s, Consume consume, std::size_t start = 0) {
    if (start == s.length()) consume(s);
    for (std::size_t i = start; i < s.length(); i++) {
        std::swap(s[start], s[i]);
        permutations(s, consume, start + 1);
    }
}

int main(void) {
    std::string s = "abcd";
    permutations(s, [](std::string s) {
        std::cout << s << std::endl;
    });
}

注記:文字が繰り返される文字列では、一意の順列は生成されません。

これを Ruby で簡単に作成しました。

def perms(x, y, possible_characters)
  all = [""]
  current_array = all.clone
  1.upto(y) { |iteration|
    next_array = []
    current_array.each { |string|
      possible_characters.each { |c|
        value = string + c
        next_array.insert next_array.length, value
        all.insert all.length, value
      }
    }
    current_array = next_array
  }
  all.delete_if { |string| string.length < x }
end

組み込みの順列型関数の言語 API を調べれば、より最適化されたコードを作成できるかもしれませんが、数値がそれほど高い場合、多くの結果を得る方法があまりあるのかわかりません。 。

とにかく、コードの背後にある考え方は、長さ 0 の文字列から開始し、次に長さ Z のすべての文字列を追跡することです (Z は反復内の現在のサイズです)。次に、各文字列を調べて、各文字を各文字列に追加します。最後に、x しきい値を下回ったものを削除し、結果を返します。

意味のない可能性のある入力 (null 文字リスト、x と y の奇妙な値など) ではテストしませんでした。

これは、Mike の Ruby バージョンを Common Lisp に翻訳したものです。

(defun perms (x y original-string)
  (loop with all = (list "")
        with current-array = (list "")
        for iteration from 1 to y
        do (loop with next-array = nil
                 for string in current-array
                 do (loop for c across original-string
                          for value = (concatenate 'string string (string c))
                          do (push value next-array)
                             (push value all))
                    (setf current-array (reverse next-array)))
        finally (return (nreverse (delete-if #'(lambda (el) (< (length el) x)) all)))))

もう 1 つのバージョンは、わずかに短く、より多くのループ機能を使用しています。

(defun perms (x y original-string)
  (loop repeat y
        collect (loop for string in (or (car (last sets)) (list ""))
                      append (loop for c across original-string
                                   collect (concatenate 'string string (string c)))) into sets
        finally (return (loop for set in sets
                              append (loop for el in set when (>= (length el) x) collect el)))))

これは単純な C# 再帰ソリューションです。

方法:

public ArrayList CalculateWordPermutations(string[] letters, ArrayList words, int index)
        {
            bool finished = true;
            ArrayList newWords = new ArrayList();
            if (words.Count == 0)
            {
                foreach (string letter in letters)
                {
                    words.Add(letter);
                }
            }

            for(int j=index; j<words.Count; j++)
            {
                string word = (string)words[j];
                for(int i =0; i<letters.Length; i++)
                {
                    if(!word.Contains(letters[i]))
                    {
                        finished = false;
                        string newWord = (string)word.Clone();
                        newWord += letters[i];
                        newWords.Add(newWord);
                    }
                }
            }

            foreach (string newWord in newWords)
            {   
                words.Add(newWord);
            }

            if(finished  == false)
            {
                CalculateWordPermutations(letters, words, words.Count - newWords.Count);
            }
            return words;
        }

電話をかける:

string[] letters = new string[]{"a","b","c"};
ArrayList words = CalculateWordPermutations(letters, new ArrayList(), 0);

Perl では、小文字のアルファベットに制限したい場合は、次のようにすることができます。

my @result = ("a" .. "zzzz");

これにより、小文字を使用した 1 ~ 4 文字のすべての可能な文字列が得られます。大文字の場合は変更します "a""A" そして "zzzz""ZZZZ".

大文字と小文字が混在する場合、それはさらに難しくなり、おそらくそのような Perl の組み込み演算子の 1 つでは実行できません。

...C バージョンは次のとおりです。

void permute(const char *s, char *out, int *used, int len, int lev)
{
    if (len == lev) {
        out[lev] = '\0';
        puts(out);
        return;
    }

    int i;
    for (i = 0; i < len; ++i) {
        if (! used[i])
            continue;

        used[i] = 1;
        out[lev] = s[i];
        permute(s, out, used, len, lev + 1);
        used[i] = 0;
    }
    return;
}

並べ替え (ABC) -> A.perm(BC) -> A.perm[B.perm(C)] -> A.perm[(*BC)、(C)B*)] -> [(*ABC)、(BC)、(BCあ*), (*ACB)、(CB)、(CBあ*)]各アルファベットチェックを挿入するときに複製を削除して、以前の文字列が同じアルファベットで終わるかどうかを確認するには(なぜですか?-エクササイズ)

public static void main(String[] args) {

    for (String str : permStr("ABBB")){
        System.out.println(str);
    }
}

static Vector<String> permStr(String str){

    if (str.length() == 1){
        Vector<String> ret = new Vector<String>();
        ret.add(str);
        return ret;
    }

    char start = str.charAt(0);
    Vector<String> endStrs = permStr(str.substring(1));
    Vector<String> newEndStrs = new Vector<String>();
    for (String endStr : endStrs){
        for (int j = 0; j <= endStr.length(); j++){
            if (endStr.substring(0, j).endsWith(String.valueOf(start)))
                break;
            newEndStrs.add(endStr.substring(0, j) + String.valueOf(start) + endStr.substring(j));
        }
    }
    return newEndStrs;
}

重複を除いてすべての順列を出力します

機能するRubyの答え:

class String
  def each_char_with_index
    0.upto(size - 1) do |index|
      yield(self[index..index], index)
    end
  end
  def remove_char_at(index)
    return self[1..-1] if index == 0
    self[0..(index-1)] + self[(index+1)..-1]
  end
end

def permute(str, prefix = '')
  if str.size == 0
    puts prefix
    return
  end
  str.each_char_with_index do |char, index|
    permute(str.remove_char_at(index), prefix + char)
  end
end

# example
# permute("abc")

C++ での再帰的ソリューション

int main (int argc, char * const argv[]) {
        string s = "sarp";
        bool used [4];
        permute(0, "", used, s);
}

void permute(int level, string permuted, bool used [], string &original) {
    int length = original.length();

    if(level == length) { // permutation complete, display
        cout << permuted << endl;
    } else {
        for(int i=0; i<length; i++) { // try to add an unused character
            if(!used[i]) {
                used[i] = true;
                permute(level+1, original[i] + permuted, used, original); // find the permutations starting with this string
                used[i] = false;
            }
        }
}

次の Java 再帰は、指定された文字列のすべての順列を出力します。

//call it as permut("",str);

public void permut(String str1,String str2){
    if(str2.length() != 0){
        char ch = str2.charAt(0);
        for(int i = 0; i <= str1.length();i++)
            permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),
                     str2.substring(1,str2.length()));
    }else{
    System.out.println(str1);
    }
}

以下は、n! を作成する上記の「permut」メソッドの更新バージョンです。上記の方法と比較して、(n 階乗) 回の再帰呼び出しが少ない

//call it as permut("",str);

public void permut(String str1,String str2){
   if(str2.length() > 1){
       char ch = str2.charAt(0);
       for(int i = 0; i <= str1.length();i++)
          permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),
                 str2.substring(1,str2.length()));
   }else{
    char ch = str2.charAt(0);
    for(int i = 0; i <= str1.length();i++)
        System.out.println(str1.substring(0,i) + ch +    str1.substring(i,str1.length()),
                 str2.substring(1,str2.length()));
   }
}
import java.util.*;

public class all_subsets {
    public static void main(String[] args) {
        String a = "abcd";
        for(String s: all_perm(a)) {
            System.out.println(s);
        }
    }

    public static Set<String> concat(String c, Set<String> lst) {
        HashSet<String> ret_set = new HashSet<String>();
        for(String s: lst) {
            ret_set.add(c+s);
        }
        return ret_set;
    }

    public static HashSet<String> all_perm(String a) {
        HashSet<String> set = new HashSet<String>();
        if(a.length() == 1) {
            set.add(a);
        } else {
            for(int i=0; i<a.length(); i++) {
                set.addAll(concat(a.charAt(i)+"", all_perm(a.substring(0, i)+a.substring(i+1, a.length()))));
            }
        }
        return set;
    }
}

これは私が思いついた JavaScript の非再帰バージョンです。これは上記の Knuth の非再帰的なものに基づいていませんが、要素の交換にはいくつかの類似点があります。最大 8 要素の入力配列に対してその正しさを検証しました。

簡単な最適化は、 out 配列と回避 push().

基本的な考え方は次のとおりです。

  1. 単一のソース配列を指定して、最初の新しい配列セットを生成します。これは、最初の要素を後続の各要素と順番に交換し、そのたびに他の要素はそのままにします。例えば:1234 が与えられると、1234、2134、3214、4231 が生成されます。

  2. 前のパスの各配列を新しいパスのシードとして使用しますが、最初の要素を交換する代わりに、2番目の要素を後続の要素と交換します。また、今回は、元の配列を出力に含めないでください。

  3. 完了するまでステップ 2 を繰り返します。

コードサンプルは次のとおりです。

function oxe_perm(src, depth, index)
{
    var perm = src.slice();     // duplicates src.
    perm = perm.split("");
    perm[depth] = src[index];
    perm[index] = src[depth];
    perm = perm.join("");
    return perm;
}

function oxe_permutations(src)
{
    out = new Array();

    out.push(src);

    for (depth = 0; depth < src.length; depth++) {
        var numInPreviousPass = out.length;
        for (var m = 0; m < numInPreviousPass; ++m) {
            for (var n = depth + 1; n < src.length; ++n) {
                out.push(oxe_perm(out[m], depth, n));
            }
        }
    }

    return out;
}

そもそもなぜこれをやりたいのかわかりません。x と y の値が適度に大きい場合、結果として得られるセットは巨大になり、x や y が大きくなるにつれて指数関数的に増加します。

使用可能な文字のセットがアルファベットの小文字 26 文字で、長さが 5 であるすべての順列を生成するようにアプリケーションに要求するとします。メモリ不足がないと仮定すると、11,881,376 が得られます (つまり、26 の 5 乗) 文字列を戻します。この長さを 6 まで上げると、308,915,776 個の文字列が返されます。これらの数値は、非常に急速に、痛ましいほど大きくなります。

これは私がJavaでまとめた解決策です。2 つの実行時引数 (x と y に対応) を指定する必要があります。楽しむ。

public class GeneratePermutations {
    public static void main(String[] args) {
        int lower = Integer.parseInt(args[0]);
        int upper = Integer.parseInt(args[1]);

        if (upper < lower || upper == 0 || lower == 0) {
            System.exit(0);
        }

        for (int length = lower; length <= upper; length++) {
            generate(length, "");
        }
    }

    private static void generate(int length, String partial) {
        if (length <= 0) {
            System.out.println(partial);
        } else {
            for (char c = 'a'; c <= 'z'; c++) {
                generate(length - 1, partial + c);
            }
        }
    }
}

今日はこれが必要でした。すでに与えられた回答は正しい方向を示してくれましたが、私が望んでいたものではありませんでした。

ここでは Heap のメソッドを使用した実装を示します。配列の長さは少なくとも 3 でなければならず、実際的な考慮事項としては、やりたいこと、忍耐力、クロック速度に応じて 10 程度を超えてはなりません。

ループに入る前に初期化します Perm(1 To N) 最初の順列では、 Stack(3 To N) ゼロを含む*、および Level2**。ループ呼び出しの終了時 NextPerm, 完了すると false が返されます。

* VB がそれを行います。

** NextPerm を少し変更してこれを不要にすることもできますが、このようにより明確になります。

Option Explicit

Function NextPerm(Perm() As Long, Stack() As Long, Level As Long) As Boolean
Dim N As Long
If Level = 2 Then
    Swap Perm(1), Perm(2)
    Level = 3
Else
    While Stack(Level) = Level - 1
        Stack(Level) = 0
        If Level = UBound(Stack) Then Exit Function
        Level = Level + 1
    Wend
    Stack(Level) = Stack(Level) + 1
    If Level And 1 Then N = 1 Else N = Stack(Level)
    Swap Perm(N), Perm(Level)
    Level = 2
End If
NextPerm = True
End Function

Sub Swap(A As Long, B As Long)
A = A Xor B
B = A Xor B
A = A Xor B
End Sub

'This is just for testing.
Private Sub Form_Paint()
Const Max = 8
Dim A(1 To Max) As Long, I As Long
Dim S(3 To Max) As Long, J As Long
Dim Test As New Collection, T As String
For I = 1 To UBound(A)
    A(I) = I
Next
Cls
ScaleLeft = 0
J = 2
Do
    If CurrentY + TextHeight("0") > ScaleHeight Then
        ScaleLeft = ScaleLeft - TextWidth(" 0 ") * (UBound(A) + 1)
        CurrentY = 0
        CurrentX = 0
    End If
    T = vbNullString
    For I = 1 To UBound(A)
        Print A(I);
        T = T & Hex(A(I))
    Next
    Print
    Test.Add Null, T
Loop While NextPerm(A, S, J)
J = 1
For I = 2 To UBound(A)
    J = J * I
Next
If J <> Test.Count Then Stop
End Sub

他の方法はさまざまな著者によって説明されています。Knuth は 2 つについて説明しています。1 つは語彙的な順序を与えますが、複雑で時間がかかり、もう 1 つは単純な変更の方法として知られています。Jie Gao と Dianjun Wang も興味深い論文を執筆しました。

ルビーでは:

str = "a"
100_000_000.times {puts str.next!}

かなり速いですが、少し時間がかかります =)。もちろん、短い文字列に興味がない場合は、「aaaaaaaa」から始めることもできます。

ただし、実際の質問を誤解している可能性があります。投稿の1つでは、文字列のブルートフォースライブラリが必要であるかのように聞こえましたが、主な質問では、特定の文字列を並べ替える必要があるように聞こえます。

あなたの問題はこれと似ています: http://beust.com/weblog/archives/000491.html (数字が繰り返されないすべての整数をリストします。その結果、ocaml 担当者は順列を使用し、一部の Java 担当者はさらに別の解決策を使用して、非常に多くの言語がこの問題を解決しました)。

Python でこのコードを呼び出すと、 allowed_characters に設定 [0,1] 最大 4 文字の場合、2^4 の結果が生成されます。

['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']

def generate_permutations(chars = 4) :

#modify if in need!
    allowed_chars = [
        '0',
        '1',
    ]

    status = []
    for tmp in range(chars) :
        status.append(0)

    last_char = len(allowed_chars)

    rows = []
    for x in xrange(last_char ** chars) :
        rows.append("")
        for y in range(chars - 1 , -1, -1) :
            key = status[y]
            rows[x] = allowed_chars[key] + rows[x]

        for pos in range(chars - 1, -1, -1) :
            if(status[pos] == last_char - 1) :
                status[pos] = 0
            else :
                status[pos] += 1
                break;

    return rows

import sys


print generate_permutations()

これがお役に立てば幸いです。数字だけでなく、あらゆる文字を扱うことができます

これは、文字列の順列を出力する方法を説明するリンクです。http://nipun-linuxtips.blogspot.in/2012/11/print-all-permutations-of-characters-in.html

これはあなたの質問に正確に答えるわけではありませんが、同じ長さの多数の文字列から文字のすべての順列を生成する 1 つの方法は次のとおりです。たとえば、単語が「coffee」、「joomla」、「moodle」の場合、「coodle」、「joodee」、「joffle」などの出力が期待できます。

基本的に、組み合わせの数は、(単語の数) の (単語あたりの文字数) 乗になります。したがって、0 から組み合わせの数 - 1 までの範囲の乱数を選択し、その数値を基数 (単語の数) に変換し、その数値の各桁を次の文字をどの単語から取得するかを示す指標として使用します。

例えば:上の例では。3 つの単語、6 文字 = 729 通りの組み合わせ。乱数を選択してください:465.基数 3 に変換します。122020。単語 1 から最初の文字を取得し、単語 2 から 2 番目の文字を取得し、単語 2 から 3 番目の文字を取得し、単語 0 から 4 番目の文字を取得します...そしてあなたは...「ジョーフル」。

すべての順列が必要な場合は、0 から 728 までループするだけです。もちろん、ランダムな値を 1 つ選択するだけの場合は、 より単純な より混乱の少ない方法は、文字をループすることです。この方法を使用すると、すべての順列が必要な場合に再帰を回避でき、さらに数学を知っているように見せることができます。(tm)!

組み合わせの数が多すぎる場合は、組み合わせを一連の小さな単語に分割し、最後にそれらを連結することができます。

C#の反復:

public List<string> Permutations(char[] chars)
    {
        List<string> words = new List<string>();
        words.Add(chars[0].ToString());
        for (int i = 1; i < chars.Length; ++i)
        {
            int currLen = words.Count;
            for (int j = 0; j < currLen; ++j)
            {
                var w = words[j];
                for (int k = 0; k <= w.Length; ++k)
                {
                    var nstr = w.Insert(k, chars[i].ToString());
                    if (k == 0)
                        words[j] = nstr;
                    else
                        words.Add(nstr);
                }
            }
        }
        return words;
    }

反復的な Java 実装があります。 アンコモンズ数学 (オブジェクトのリストに対して機能します):

/**
 * Generate the indices into the elements array for the next permutation. The
 * algorithm is from Kenneth H. Rosen, Discrete Mathematics and its 
 * Applications, 2nd edition (NY: McGraw-Hill, 1991), p. 284)
 */
private void generateNextPermutationIndices()
{
    if (remainingPermutations == 0)
    {
        throw new IllegalStateException("There are no permutations " +
             "remaining. Generator must be reset to continue using.");
    }
    else if (remainingPermutations < totalPermutations)
    {
        // Find largest index j with 
        // permutationIndices[j] < permutationIndices[j + 1]
        int j = permutationIndices.length - 2;
        while (permutationIndices[j] > permutationIndices[j + 1])
        {
            j--;
        }

        // Find index k such that permutationIndices[k] is smallest integer 
        // greater than permutationIndices[j] to the right
        // of permutationIndices[j].
        int k = permutationIndices.length - 1;
        while (permutationIndices[j] > permutationIndices[k])
        {
            k--;
        }

        // Interchange permutation indices.
        int temp = permutationIndices[k];
        permutationIndices[k] = permutationIndices[j];
        permutationIndices[j] = temp;

        // Put tail end of permutation after jth position in increasing order.
        int r = permutationIndices.length - 1;
        int s = j + 1;

        while (r > s)
        {
            temp = permutationIndices[s];
            permutationIndices[s] = permutationIndices[r];
            permutationIndices[r] = temp;
            r--;
            s++;
        }
    }
    --remainingPermutations;
}

/**
 * Generate the next permutation and return a list containing
 * the elements in the appropriate order.  This overloaded method
 * allows the caller to provide a list that will be used and returned.
 * The purpose of this is to improve performance when iterating over
 * permutations.  If the {@link #nextPermutationAsList()} method is
 * used it will create a new list every time.  When iterating over
 * permutations this will result in lots of short-lived objects that
 * have to be garbage collected.  This method allows a single list
 * instance to be reused in such circumstances.
 * @param destination Provides a list to use to create the
 * permutation.  This is the list that will be returned, once
 * it has been filled with the elements in the appropriate order.
 * @return The next permutation as a list.
 */
public List<T> nextPermutationAsList(List<T> destination)
{
    generateNextPermutationIndices();
    // Generate actual permutation.
    destination.clear();
    for (int i : permutationIndices)
    {
        destination.add(elements[i]);
    }
    return destination;
}

完全なソース

def gen( x,y,list): #to generate all strings inserting y at different positions
list = []
list.append( y+x )
for i in range( len(x) ):
    list.append( func(x,0,i) + y + func(x,i+1,len(x)-1) )
return list 

def func( x,i,j ): #returns x[i..j]
z = '' 
for i in range(i,j+1):
    z = z+x[i]
return z 

def perm( x , length , list ): #perm function
if length == 1 : # base case
    list.append( x[len(x)-1] )
    return list 
else:
    lists = perm( x , length-1 ,list )
    lists_temp = lists #temporarily storing the list 
    lists = []
    for i in range( len(lists_temp) ) :
        list_temp = gen(lists_temp[i],x[length-2],lists)
        lists += list_temp 
    return lists
def permutation(str)
  posibilities = []
  str.split('').each do |char|
    if posibilities.size == 0
      posibilities[0] = char.downcase
      posibilities[1] = char.upcase
    else
      posibilities_count = posibilities.length
      posibilities = posibilities + posibilities
      posibilities_count.times do |i|
        posibilities[i] += char.downcase
        posibilities[i+posibilities_count] += char.upcase
      end
    end
  end
  posibilities
end

非再帰バージョンについての私の見解は次のとおりです

Python のソリューション:

from itertools import permutations
s = 'ABCDEF'
p = [''.join(x) for x in permutations(s)]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top