gpt4 book ai didi

language-agnostic - 如何在给定长度内找到k的排列?

转载 作者:行者123 更新时间:2023-12-04 18:53:38 25 4
gpt4 key购买 nike

如何在给定长度内找到 k 的排列?

例如:

cat有 3 个字母:如何在单词 cat 中找到 2 的所有排列.
结果应该是:ac , at , ca , ac , 等等...

这不是家庭作业问题。
可以使用任何语言,但更可取:C/C++ 或 C#。
我知道如何为大小 LENGTH 创建递归,但不知道如何为自定义大小创建递归。

最佳答案

这是 C# 中的一个,即使使用重复的字符也应该可以使用。例如,对于长度为 2 的排列的“香蕉”,它给出:

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

这是我拥有的完整程序,可以使用它:
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;
}
}
}

关于language-agnostic - 如何在给定长度内找到k的排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2350211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com