gpt4 book ai didi

c# - 列出字符串/整数的所有排列

转载 作者:IT王子 更新时间:2023-10-29 03:31:30 24 4
gpt4 key购买 nike

编程面试中的一个常见任务(虽然不是根据我的面试经验)是获取一个字符串或一个整数并列出所有可能的排列。

是否有示例说明如何完成此操作以及解决此类问题背后的逻辑?

我看过一些代码片段,但它们没有得到很好的注释/解释,因此很难理解。

最佳答案

首先:当然,它闻起来像递归!

既然你也想知道原理,那我就尽量用人话来解释了。我认为大多数时候递归非常容易。你只需要掌握两个步骤:

  1. 第一步
  2. 所有其他步骤(都具有相同的逻辑)

人类语言:

In short:

  1. The permutation of 1 element is one element.
  2. The permutation of a set of elements is a list each of the elements, concatenated with every permutation of the other elements.

Example:

If the set just has one element -->
return it.
perm(a) -> a

If the set has two characters: foreach element in it: return theelement, with the permutation of therest of the elements added, like so:

perm(ab) ->

a + perm(b) -> ab

b + perm(a) -> ba

Further: for each character in the set: return a character, concatenated with a permutation of > the rest of the set

perm(abc) ->

a + perm(bc) --> abc, acb

b + perm(ac) --> bac, bca

c + perm(ab) --> cab, cba

perm(abc...z) -->

a + perm(...), b + perm(....)
....

我在 http://www.programmersheaven.com/mb/Algorithms/369713/369713/permutation-algorithm-help/ 上找到了伪代码 :

makePermutations(permutation) {
if (length permutation < required length) {
for (i = min digit to max digit) {
if (i not in permutation) {
makePermutations(permutation+i)
}
}
}
else {
add permutation to list
}
}

C#

好的,还有更详细的东西(因为它被标记为 c#),来自 http://radio.weblogs.com/0111551/stories/2002/10/14/permutations.html :相当冗长,但我还是决定复制它,所以这篇文章不依赖于原文。

The function takes a string of characters, and writes down every possible permutation of that exact string, so for example, if "ABC" has been supplied, should spill out:

ABC、ACB、BAC、BCA、CAB、CBA。

代码:

class Program
{
private static void Swap(ref char a, ref char b)
{
if (a == b) return;

var temp = a;
a = b;
b = temp;
}

public static void GetPer(char[] list)
{
int x = list.Length - 1;
GetPer(list, 0, x);
}

private static void GetPer(char[] list, int k, int m)
{
if (k == m)
{
Console.Write(list);
}
else
for (int i = k; i <= m; i++)
{
Swap(ref list[k], ref list[i]);
GetPer(list, k + 1, m);
Swap(ref list[k], ref list[i]);
}
}

static void Main()
{
string str = "sagiv";
char[] arr = str.ToCharArray();
GetPer(arr);
}
}

关于c# - 列出字符串/整数的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/756055/

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