Y_Y*_*Y_Y 5 language-agnostic permutation
如何找到给定长度的k的排列?
例如:
这个单词cat有3个字母:如何找到单词2的所有排列cat。结果应该是:ac,at,ca,ac,等...
这不是作业问题。可以使用任何语言,但更可取的是:C / C ++或C#。我知道如何为长度LENGTH创建递归,但不为自定义大小创建递归。
小智 3
这是 C# 中的一个,即使处理重复的字符也应该可以工作。例如,对于长度为 2 的排列“banana”,它给出:
ba bn ab aa an nb na nn
基本思想是固定第一个字符,然后形成长度为 k-1 的所有排列,然后将字符添加到这些 k-1 长度排列之前。为了处理重复的字符,我们跟踪剩余的字符数(即可用于子排列的字符)。
不是示例代码,但应该可以给您带来想法。(如果您发现错误,请告诉我,我可以编辑)。
static List<string> Permutations(Dictionary<char, int> input, int length) {
List<string> permutations = new List<string>();
List<char> chars = new List<char>(input.Keys);
// Base case.
if (length == 0) {
permutations.Add(string.Empty);
return permutations;
}
foreach (char c in chars) {
// There are instances of this character left to use.
if (input[c] > 0) {
// Use one instance up.
input[c]--;
// Find sub-permutations of length length -1.
List<string> subpermutations = Permutations(input, length - 1);
// Give back the instance.
input[c]++;
foreach (string s in subpermutations) {
// Prepend the character to be the first character.
permutations.Add(s.Insert(0,new string(c,1)));
}
}
}
return permutations;
}
Run Code Online (Sandbox Code Playgroud)
这是我使用它的完整程序:
using System;
using System.Collections.Generic;
namespace StackOverflow {
class Program {
static void Main(string[] args) {
List<string> p = Permutations("abracadabra", 3);
foreach (string s in p) {
Console.WriteLine(s);
}
}
static List<string> Permutations(string s, int length) {
Dictionary<char, int> input = new Dictionary<char, int>();
foreach (char c in s) {
if (input.ContainsKey(c)) {
input[c]++;
} else {
input[c] = 1;
}
}
return Permutations(input, length);
}
static List<string> Permutations(Dictionary<char, int> input,
int length) {
List<string> permutations = new List<string>();
List<char> chars = new List<char>(input.Keys);
if (length == 0) {
permutations.Add(string.Empty);
return permutations;
}
foreach (char c in chars) {
if (input[c] > 0) {
input[c]--;
List<string> subpermutations = Permutations(input,
length - 1);
input[c]++;
foreach (string s in subpermutations) {
permutations.Add(s.Insert(0,new string(c,1)));
}
}
}
return permutations;
}
}
}
Run Code Online (Sandbox Code Playgroud)