排列、递归
我有一个作业:用户输入一个字符串,例如 ABCD,程序必须给出所有排列。 我不想要整个代码只是一个提示。这就是我到目前为止所得到的,我没有任何实施。
以ABCD为例:
获取字符串长度的阶乘,本例为4! = 24.
24/4 = 6 所以第一个字母必须在 6 之后改变。到目前为止一切顺利。
比得到剩余字母的阶乘,即三个 3! = 6.
6/3 =2 每个字母 2 个位置。从这里开始我不知道它如何能够继续填补24个位置。
通过这个算法,我将拥有的是
ABCD
ABD
AC
AC
AD
AD
B
B
B
B
B
B
。
。 (继续 6 C 和 6 D)
我认为我的问题是我在递归问题上没有很多经验,所以谁可以建议一些程序来编程以帮助我更好地了解递归,请这样做。
谢谢!如果有不清楚的地方请指出。
I have an assignment: User enters a String, example ABCD and the program has to give out alll the permutations.
I don't want the whole code just a tip. this is what i got so far in thery i got nothing implemented.
Taking ABCD as an example:
get factorial of length of String in this case 4! = 24.
24/4 = 6 So first letter has to change after 6. so far so good.
than get factorial of remaining letters which are three 3! = 6.
6/3 =2 2 places for each letter. from here i don't know how it can continue to fill 24 places.
With this algorithm all i will have is
ABCD
ABD
AC
AC
AD
AD
B
B
B
B
B
B
.
. (continues with 6 C's and 6 D's)
I think my problem is i do not have alot of experience with recursive problems so who can suggest some programs to program to help me get to know recursion better please do.
Thanks! If somethings aren't clear please point out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的,递归是要走的路。你通过一点数学计算得出的例子是完全正确的,但有点间接。
这是一些伪代码:
部分递归树的示例
编辑
处理重复的字符而不重复任何排列。令
unique
为一个函数,用于从集合(或通过索引被视为有序字符集合的字符串)中删除任何重复元素。1) 存储结果(包括重复项),然后将其过滤掉
2) 首先避免生成重复项
You are right that recursion is the way to go. The example you worked thru w/ the little bit of math was all correct, but kind of indirect.
Here's some pseudocode:
example of partial recursion tree
EDIT
To handle repeated characters without duplicating any permutations. Let
unique
be a function to remove any repeated elements from a collection (or string that is being treated like an ordered character collection thru indexing).1) Store results (including dupes), filter them out afterwards
2) Avoid generating duplicates in the first place
创建一个接受字符串的方法。
从字符串中挑选一个字母并输出。
使用输入字符串减去您选择的字母创建一个新字符串。
如果新字符串至少有 1 个字符,则使用新字符串调用上述方法,
为每个可能的字母选择一个字母。
Make a method that takes a string.
Pick a letter out of the string and output it.
Create a new string with the input string minus the letter you picked.
call the above method with the new string if it has at least 1 character
do this picking of one letter for each possible letter.