题目:输入一个字符串,打印出该字符串中字符的所有的排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串。
解题思路:把字符串分为两部分,一部分是字符串的第一个字符,另一部分是第一个字符以后的所有字符。接下来求第一个字符以后的所有字符的排列。拿第一个字符和它后面的字符串逐个交换。
C#实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public
static
void
Permutation(
char
[] pStr)
{
if
(pStr ==
null
)
return
;
int
begin = 0;
Permutation(pStr, begin);
}
private
static
void
Permutation(
char
[] pStr,
int
begin)
{
if
(begin == pStr.Length)
Console.WriteLine(pStr);
else
{
for
(
int
i = begin; i < pStr.Length; i++)
{
char
temp = pStr[i];
pStr[i] = pStr[begin];
pStr[begin] = temp;
Permutation(pStr, begin + 1);
temp = pStr[i];
pStr[i] = pStr[begin];
pStr[begin] = temp;
}
}
}
|
Java实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public
static
void
permutation(
char
[] pStr) {
if
(pStr ==
null
)
return
;
int
begin =
0
;
permutation(pStr, begin);
}
private
static
void
permutation(
char
[] pStr,
int
begin) {
if
(begin == pStr.length)
System.out.println(pStr);
else
{
for
(
int
i = begin; i < pStr.length; i++) {
char
temp = pStr[i];
pStr[i] = pStr[begin];
pStr[begin] = temp;
permutation(pStr, begin +
1
);
temp = pStr[i];
pStr[i] = pStr[begin];
pStr[begin] = temp;
}
}
}
|
Python实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
def
permutation(pStr):
if
pStr
=
=
None
:
return
begin
=
0
permutation_child(pStr, begin)
def
permutation_child(pStr, begin):
if
begin
=
=
len
(pStr):
print
(pStr)
else
:
for
i
in
range
(begin,
len
(pStr)):
temp
=
pStr[i]
pStr[i]
=
pStr[begin]
pStr[begin]
=
temp
permutation_child(pStr, begin
+
1
)
temp
=
pStr[i]
pStr[i]
=
pStr[begin]
pStr[begin]
=
temp
|
本文转自 许大树 51CTO博客,原文链接:http://blog.51cto.com/abelxu/1978056,如需转载请自行联系原作者