生成没有相邻字符的字符串的所有排列的算法

Algorithm to generating all permutations of a string with no adjacent characters

假设我有 ABCDEF。然后,有6个!重新排序该字符串的排列。现在,我只想处理没有相邻字符的排列。这意味着,我想查看满足这些约束的所有排列:

我对该算法的处理方法是以下伪代码:

//generate all 6! permutations
//check all permutations and see where B is next to A || C
    //remove all instances
//check all permutations and see where C is next to D
    //remove all instances
//check all permutations and see where D is next to E
    //remove all instances
//check all permutations and see where E is next to F 
    //remove all instances

但是,这些掩码操作变得非常低效并且花费了我太多时间,尤其是当我的字符串长度大于 6 时。我怎样才能更有效地做到这一点?我看到了这些类似的帖子,1, 2,希望从中提取一些可能对我有帮助的关键想法。然而,这也是暴力检查。我想从一开始就只生成独特的模式,而不是生成所有的东西然后一个一个地检查。

编辑: 目前这是我用来生成所有排列的方法。

static String[] designs;
static int index;
protected static String[] generateDesigns(int lengthOfSequence, int numOfPermutations){
    designs = new String[numOfPermutations];
    StringBuilder str = new StringBuilder("1");
    for(int i = 2; i <= lengthOfSequence; i++)
        str.append(i);

    genDesigns("", str.toString()); //genDesigns(6) = 123456 will be the unique characters
    return designs;
}

//generate all permutations for lenOfSequence characters
protected static void genDesigns(String prefix, String data){
    int n = data.length();
    if (n == 0) designs[index++] = prefix;
    else {
        for (int i = 0; i < n; i++)
            genDesigns(prefix + data.charAt(i), data.substring(0, i) + data.substring(i+1, n));
    }
}

生成长度为n的字符串的所有排列的算法的典型O(n!)伪代码:

function permute(String s, int left, int right)
{
   if (left == right)
     print s
   else
   {
       for (int i = left; i <= right; i++)
       {
          swap(s[left], s[i]);
          permute(s, left + 1, right);
          swap(s[left], s[i]); // backtrack
       }
   }
}

字符串 ABC 对应的递归树看起来像 [图片来自互联网]:

在交换之前,检查是否可以交换满足给定的约束(检查 s[left]s[i] 的新的前一个和新的下一个字符)。这也会从递归树中删除许多分支。

这是一个相当简单的回溯解决方案,在将相邻字符添加到排列之前修剪搜索。

public class PermutationsNoAdjacent {

    private char[] inputChars;
    private boolean[] inputUsed;
    private char[] outputChars;
    private List<String> permutations = new ArrayList<>();

    public PermutationsNoAdjacent(String inputString) {
        inputChars = inputString.toCharArray();
        inputUsed = new boolean[inputString.length()];
        outputChars = new char[inputString.length()];
    }

    private String[] generatePermutations() {
        tryFirst();
        return permutations.toArray(new String[permutations.size()]);
    }

    private void tryFirst() {
        for (int inputIndex = 0; inputIndex < inputChars.length; inputIndex++) {
            assert !inputUsed[inputIndex] : inputIndex;
            outputChars[0] = inputChars[inputIndex];
            inputUsed[inputIndex] = true;
            tryNext(inputIndex, 1);
            inputUsed[inputIndex] = false;
        }
    }

    private void tryNext(int previousInputIndex, int outputIndex) {
        if (outputIndex == outputChars.length) { // done
            permutations.add(new String(outputChars));
        } else {
            // avoid previousInputIndex and adjecent indices
            for (int inputIndex = 0; inputIndex < previousInputIndex - 1; inputIndex++) {
                if (!inputUsed[inputIndex]) {
                    outputChars[outputIndex] = inputChars[inputIndex];
                    inputUsed[inputIndex] = true;
                    tryNext(inputIndex, outputIndex + 1);
                    inputUsed[inputIndex] = false;
                }
            }
            for (int inputIndex = previousInputIndex + 2; inputIndex < inputChars.length; inputIndex++) {
                if (!inputUsed[inputIndex]) {
                    outputChars[outputIndex] = inputChars[inputIndex];
                    inputUsed[inputIndex] = true;
                    tryNext(inputIndex, outputIndex + 1);
                    inputUsed[inputIndex] = false;
                }
            }
        }
    }

    public static void main(String... args) {
        String[] permutations = new PermutationsNoAdjacent("ABCDEF").generatePermutations();
        for (String permutation : permutations) {
            System.out.println(permutation);
        }
    }

}

它打印 ABCDEF 的 90 个排列。我只引用开头和结尾:

ACEBDF
ACEBFD
ACFDBE
ADBECF
…
FDBEAC
FDBECA