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

时间:2016-11-12 16:15:09

标签: java string algorithm permutation

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

  • B不在A或C旁边
  • C不在B或D旁边
  • D不在C或E旁边
  • E不在D或F旁边

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

//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.我怎样才能更有效地做到这一点?我看到这些类似的帖子12,并希望提取一些可能对我有帮助的重要提示。但是,这也是强力检查。我想从头开始实际生成唯一的模式,而不必生成所有内容并逐个检查。

编辑:目前我正在使用它来生成所有排列。

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));
    }
}

2 个答案:

答案 0 :(得分:5)

用于生成长度为O(n!)的字符串的所有排列的典型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的相应递归树看起来像[从互联网上拍摄的图像]:

enter image description here

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

答案 1 :(得分:0)

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

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