问题描述:给定一个数组,数字中数字不重复,求所有全排列。

算法分析:可以用交换递归法,也可以用插入法。

递归法:例如,123,先把1和1交换,然后递归全排列2和3,然后再把1和1换回来。1和2交换,全排列1和3,再把1和2交换回来。1和3交换,全排列2和1,再把1和3交换回来。

//递归方法
public List<List<Integer>> permute2(int[] num) {
List<List<Integer>> result = new ArrayList<>();
permute(num, 0, result);
return result;
} void permute(int[] num, int start, List<List<Integer>> result) { if (start == num.length)
{
ArrayList<Integer> item = convertArrayToList(num);
//List<int[]> list = Arrays.asList(num);这个方法适合String,而不适合int,会把int[]当成一个元素加入list
result.add(item);
}
for (int j = start; j < num.length; j++)
{
//递归方法,首先1和1交换,求除nums[1]外的序列的全排列,然后1和1再交换回来。1和2交换,求除了nums[1]之外的序列的全排列,然后1和2再交换回来。
swap(num, start, j);
permute(num, start + 1, result);
swap(num, start, j);
}
} private ArrayList<Integer> convertArrayToList(int[] num) {
ArrayList<Integer> item = new ArrayList<Integer>();
for (int h = 0; h < num.length; h++) {
item.add(num[h]);
}
return item;
} private void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

插入法:例如123,1开始有1个插入位置得到序列[1],然后2有两个插入位置,得到序列[2,1],[1,2],然后3有三个插入位置,得到[3,2,1],[2,3,1],[2,1,3],[3,1,2],[1,3,2],[1,2,3]

public List<List<Integer>> permute(int[] num) {
List<List<Integer>> result = new ArrayList<>();
//start from an empty list
result.add(new ArrayList<Integer>()); for (int i = 0; i < num.length; i++)
{
List<List<Integer>> current = new ArrayList<>(); for (List<Integer> l : result)
{
//插入size+1个位置
for (int j = 0; j < l.size()+1; j++)
{
l.add(j, num[i]);
ArrayList<Integer> temp = new ArrayList<Integer>(l);
current.add(temp);
l.remove(j);
}
} result = new ArrayList<>(current);
} return result;
}

最新文章

  1. 【SAP BO】【DI】DataService 服务无法启动。错误1069:由于登录失败而无法启动服务
  2. [问题2014A09] 复旦高等代数 I(14级)每周一题(第十一教学周)
  3. JMeter中3种参数值的传递
  4. Leetcode#115 Distinct Subsequences
  5. underscore demo
  6. Linux下文件轻松比对,自由开源的比较软件
  7. 运行tomcat7w.exe tomcat7.exe ,提示 指定的服务未安装 unable to open the service &#39;tomcat7&#39;
  8. 怎么提高ArcGIS for Desktop10.x的性能
  9. cocos2d-x protobuf; cocos2dx protocol buffer
  10. 关于使用Xcode9.0使用[UIImage imageNamed:]返回null的问题
  11. 常用的lamp环境以及一些依赖包的安装
  12. Eclipse常用快捷键--摘录他人
  13. spring的基于XML方式的属性注入
  14. gcc -O0 -O1 -O2 -O3 四级优化选项及每级分别做什么优化
  15. python第六十天-----RabbitMQ
  16. Spring容器AOP的实现原理——动态代理(转)
  17. 06-jQuery的文档操作(重点)
  18. lambda、map、reduce、filter函数讲解
  19. k8s 健康检查
  20. python3 AttributeError: module &#39;sklearn&#39; has no attribute &#39;linear_model&#39;

热门文章

  1. Oracle的聚合函数group by结合CUBE和ROLLUP的使用
  2. maven 的构建异常 Could not find artifact ... and &#39;parent.relativePath&#39;
  3. FineReport---数据集
  4. windows 全角 怎么切换到半角
  5. Sending &#39;ccColor4B&#39; (aka &#39;struct_ccColor4B&#39;) to parameter of incompatible type
  6. C#中的另类语法
  7. 洛谷 P2300 合并神犇
  8. JVM虚拟机—JVM的垃圾回收机制(转载)
  9. Python3 标准库
  10. composer 常用包管理工具