生成字符串列表及其子字符串的排列的算法

标签 algorithm list permutation

我已经逃避这个算法一段时间了。假设我得到了字符串“cccaatt”。我正在尝试生成重复字母的每个子串的所有可能变体。 EG,“cccaatt”作为输入将返回:

猫, 猫, 猫, 猫, 猫猫, ccatt, ccaat, ccaatt, 猫猫, CCAT, 关注, 访问权限

结果的顺序无关紧要,只要返回所有结果即可。一般来说,输入是一个字符串,由g组重复的字母组成,每组k_n个字母长。

我的直觉是这是一个递归算法,但它的确切结构一直难以理解。

最佳答案

如果您存储字母表和每个字母的最大出现次数(正如评论中提到的那样),您可以这样做:

function variations(letter_type, current string) {
    if (letter_type is in the alphabet) {
        while (string has fewer than the max amount of that letter) {
            add one of that letter to current string
            variations(next letter, current string)
        }
    } else {
        print current string // since there are no more letters to add
    }
}

在 Java 中:

public class Variations {

    static String[] alphabet = {"c","a","t"};
    static int[] maximums = {3, 2, 2};

    public static void main(String[] args) {
        variations(0, "");
    }

    public static void variations(int letter_type, String curr) {
        if (letter_type < alphabet.length) {
            for (int i = 1; i <= maximums[letter_type]; i++) {
            curr += alphabet[letter_type];
            variations(letter_type+1, curr);
            }
        } else {
            System.out.println(curr);
        } 
    }

}

关于生成字符串列表及其子字符串的排列的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12273688/

相关文章:

algorithm - 查找对应于总和列表的一组对

algorithm - 如何在完全二叉树的最后一层中找到最右边的节点的位置?

python - 从列表中删除 unicode 'u' 的最简单方法是什么

c# - IQueryable、ICollection、IList 和 IDictionary 接口(interface)之间的区别

python - 根据列表中的条件合并列表项

algorithm - 克鲁斯卡尔算法如何贪婪?

algorithm - 在 F# 中计算排列

python - 具有多个列表和条件的排列

c - 一个词的所有可能组合

具有概率成对比较的模糊排序算法