반복 문자로도 작동합니다 C#의 하나입니다. 길이 2의 순열을위한 "바나나"에 대한 예를 들어 그것을 제공 : AB의 AA 억
바에게주의를 노나 윈
기본적인 아이디어는 다음, 첫 번째 문자를 고정 길이의 모든 순열을 형성하는
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;
}
그리고 여기가 내가 가지고있는 전체 프로그램입니다, 그것을 사용하는 : 내가 잘못 본게 아니라면
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;
}
}
}
특정 언어가 있습니까? –
숙제 문제 같은 것 같습니다. –
아니요 ... 숙제 문제가 아니며 모든 언어를 사용할 수 있지만 더 선호합니다 : C/C++ 또는 C#. –