递归算法--如何一步一步理解递归(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
相关文章推荐
- 递归算法--如何一步一步理解递归(1)
- 递归算法详细分析(如何更好的理解递归)
- 如何理解递归
- 对面试题“输入n,求一个nXn矩阵,规定矩阵沿45度递增,形成一个zigzag数组(JPEG编码里取像素数据的排列顺序),请问如何用C++实现?”的理解
- 递归三部曲之深入理解全排列
- 康拓排列的自我总结--以及全排列的递归非递归算法
- 如何一步一步用DDD设计一个电商网站(一)—— 先理解核心概念
- NOI2.2基本算法之递归和自调用函数 全排列 分析----如何写全排列函数
- 如何理解递归?
- 如何理解递归
- 如何理解汉诺塔的递归?
- 深入理解递归:全排列问题
- [算法]递归算法中sort的递归理解以及原地归并和自顶向下递归排序
- 到底如何理解递归?
- 如何理解递归
- 如何通俗理解递归
- 如何通俗的理解递归
- 由合并排序算法谈如何理解递归
- 【递归算法】人脑理解递归
- 如何去理解递归,想到递归,运用递归