您的位置:首页 > 其它

递归算法--如何一步一步理解递归(2)--全排列

2017-09-06 20:54 253 查看

全排列定义:

从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。


核心代码:

public static int total = 0;
public static void swap(String[] str, int i, int j) {
String temp = new String();
temp = str[i];
str[i] = str[j];
str[j] = temp;
}

public static void arrange(String[] str, int st, int len) {
if (st == len - 1) {
for (int i = 0; i < len; i++) {
System.out.print(str[i] + " -- ");
}
System.out.println();
total++;
} else {
for (int i = st; i < len; i++) {
swap(str, st, i);
arrange(str, st + 1, len);
swap(str, st, i);
}
}

}


具体实现代码:

package test;

public class permutate {
public static int total = 0; public static void swap(String[] str, int i, int j) { String temp = new String(); temp = str[i]; str[i] = str[j]; str[j] = temp; } public static void arrange(String[] str, int st, int len) { if (st == len - 1) { for (int i = 0; i < len; i++) { System.out.print(str[i] + " -- "); } System.out.println(); total++; } else { for (int i = st; i < len; i++) { swap(str, st, i); arrange(str, st + 1, len); swap(str, st, i); } } }
public static void main(String[] args) {
String str[] = { "a", "b", "c"};
arrange(str, 0, str.length);
System.out.println(total);
}
}


运行结果:

a -- b -- c --
a -- c -- b --
b -- a -- c --
b -- c -- a --
c -- b -- a --
c -- a -- b --
6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  递归算法 全排列