【问题标题】:I want to get a specific combination of permutation?我想得到一个特定的排列组合?
【发布时间】:2012-03-15 10:01:21
【问题描述】:

我想得到像字母表这样的字符串排列的特定组合。为了理解我,我将向您展示我使用的代码:

public class PermutationExample {

public static List<String> getPermutation(String input) {

    List<String> collection = null;

    if (input.length() == 1) {
        collection = new ArrayList<String>();
        collection.add(input);
        return collection;
    } else {
        collection = getPermutation(input.substring(1));
        Character first = input.charAt(0);
        List<String> result = new ArrayList<String>();
        for (String str : collection) {
            for (int i = 0; i < str.length(); i++) {
                String item = str.substring(0, i) + first
                        + str.substring(i);
                result.add(item);
            }
            String item = str.concat(first.toString());
            result.add(item);
        }
        return result;
    }

}

public static void main(String[] args) {
    System.out.println(PermutationExample.getPermutation("ABCD"));

}
}

这段代码运行良好,我可以得到每个组合,我可以从列表中获取它,如果我需要第 5 个元素,我可以接收它。但是如果字符串是字母 ... ,则不起作用,它太大了。我必须做的是,从所有 26 个中获取特定元素,例如 1221-th!组合?

【问题讨论】:

    标签: java cryptography


    【解决方案1】:

    我不久前解决了一个类似的问题,只是在 python 中。

    如果您需要的只是第 n 个排列,那么如果您尝试考虑只生成您需要的排列,那么您可以做得比生成每个排列并返回第 n 个更好。

    您可以“简单”地做到这一点,方法是找出您想要的排列数量的前面的元素应该是什么,然后递归地找出剩余的元素应该是什么。

    假设任何值的集合值 [0, ... ,X] 满足 col[n]

    我们将看到每个(N-1)之后集合头部的变化!排列,所以如果 n

    这有帮助吗?我知道这是相当高的水平,你必须考虑一下,但也许它会让你走上正轨。

    【讨论】:

    • 是的,我需要字符串的第 N 个排列,但我不知道如何解决这个问题:/
    猜你喜欢
    • 1970-01-01
    • 2015-10-25
    • 2019-04-02
    • 2023-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多