【LeetCode】Permutations 解题报告
全排列问题。经常使用的排列生成算法有序数法、字典序法、换位法(Johnson(Johnson-Trotter)、轮转法以及Shift cursor cursor* (Gao & Wang)法。
【题目】
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2],
and [3,2,1].
【暴力递归】
这是比較直观的思路。可是也有要注意的地方。刚開始写的时候,没有注意到list是共用的。所曾经面得到的答案后面会改掉而导致错误。
public class Solution {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
public List<List<Integer>> permute(int[] num) {
int len = num.length;
if (len == 0) return ret;
List<Integer> list = new ArrayList<Integer>();
run(list, num);
return ret;
}
public void run(List<Integer> list, int[] num) {
if (list.size() == num.length) {
//注意这里要又一次new一个list。要不然后面会被改动
List<Integer> res = new ArrayList<Integer>();
res.addAll(list);
ret.add(res);
return;
}
for (int i = 0; i < num.length; i++) {
if (list.contains(num[i])) {
continue;
}
list.add(num[i]);
run(list, num);
list.remove(list.indexOf(num[i])); //不要忘记这一步
}
}
}
【字典序法】
C++的STL库里面有nextPermutation()方法。事实上现就是字典序法。
下图简单明了地介绍了字典序法
归纳一下为:
比如,1234的全排列例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGppYWJpbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
【代码实现】
因为Java的list传參传的是地址,所以每次加入时都要记得又一次new一个新的list加入到结果集中。否则加入到结果集中的原list会被后面的操作改变。
public class Solution {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
int len = num.length;
if (len == 0) return ret;
Arrays.sort(num); //字典序法需先对数组升序排序
//数组转为list
List<Integer> list0 = new ArrayList<Integer>();
for (int i = 0; i < len; i++) {
list0.add(num[i]);
}
//把原始数组相应的list加入到结果中。不能直接加入list0,由于后面它会一直变化
List<Integer> ll = new ArrayList<Integer>();
ll.addAll(list0);
ret.add(ll);
//逐次找下一个排列
for (int i = 1; i < factorial(len); i++) {
ret.add(nextPermutation(list0));
}
return ret;
}
/***字典序法生成下一个排列***/
public List<Integer> nextPermutation(List<Integer> num) {
//找到最后一个正序
int i = num.size()-1;
while(i > 0 && num.get(i-1) >= num.get(i)){
i--;
}
//找到最后一个比num[i-1]大的数
int j = i;
while(j < num.size() && num.get(j) > num.get(i-1)) {
j++;
}
//交换num[i-1]和num[j-1]
int tmp = num.get(i - 1);
num.set(i - 1, num.get(j - 1));
num.set(j - 1, tmp);
//反转i以后的数
reverse(num, i, num.size()-1);
List<Integer> ret = new ArrayList<Integer>();
ret.addAll(num);
return ret;
}
public void reverse(List<Integer> list, int begin, int end) {
for(int i = begin, j = end; i < j; i++) {
list.add(i, list.remove(j));
}
}
public int factorial(int n) {
return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}
}
上面的实现须要先对原数组升序排序。以下对nextPermutation(List<Integer> num)改进后就不用对num排序了。
/***字典序法生成下一个排列***/
public List<Integer> nextPermutation(List<Integer> num) {
//找到最后一个正序
int i = num.size()-1;
while(i > 0 && num.get(i-1) >= num.get(i)){
i--;
} //有了这个推断就不用num最初是按升序排好的了
if (i == 0) {
reverse(num, 0, num.size()-1);
List<Integer> ret = new ArrayList<Integer>();
ret.addAll(num);
return ret;
} //找到最后一个比num[i-1]大的数
int j = i;
while(j < num.size() && num.get(j) > num.get(i-1)) {
j++;
} //交换num[i-1]和num[j-1]
int tmp = num.get(i - 1);
num.set(i - 1, num.get(j - 1));
num.set(j - 1, tmp); //反转i以后的数
reverse(num, i, num.size()-1); List<Integer> ret = new ArrayList<Integer>();
ret.addAll(num);
return ret;
}
欢迎高人对上述代码继续优化!
相关题目:【LeetCode】Next Permutation 解题报告 和 【LeetCode】Permutations II 解题报告
【LeetCode】Permutations 解题报告的更多相关文章
- LeetCode: Permutations 解题报告
Permutations Given a collection of numbers, return all possible permutations. For example,[1,2,3] ha ...
- 【LeetCode】46. Permutations 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 方法一:库函数 方法二:递归 方法三:回溯法 日期 题目地址:h ...
- leetcode—Palindrome 解题报告
1.题目描述 Given a string s, partition s such that every substring of the partition is a palindrome. Ret ...
- LeetCode C++ 解题报告
自己做得LeetCode的题解,使用C++语言. 说明:大多数自己做得,部分参考别人的思路,仅供参考; GitHub地址:https://github.com/amazingyyc/The-Solut ...
- C++版 - 剑指offer之面试题37:两个链表的第一个公共结点[LeetCode 160] 解题报告
剑指offer之面试题37 两个链表的第一个公共结点 提交网址: http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?t ...
- LeetCode: Subsets 解题报告
Subsets Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset ...
- LeetCode: Triangle 解题报告
Triangle Given a triangle, find the minimum path sum from top to bottom. Each step you may move to a ...
- LeetCode: isSameTree1 解题报告
isSameTree1 Given two binary trees, write a function to check if they are equal or not. Two binary t ...
- LeetCode: Combinations 解题报告
Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ... ...
随机推荐
- C#两个DataTable拷贝问题:该行已经属于另一个表的解决方法
一.DataTable.Rows.Add(DataRow.ItemArray); 二.DataTable.ImportRow(DataRow) 三.设置DataTable的tablename,然后.R ...
- jmeter 签名MD5生成
请求接口需要同时发送签名,签名定义为: 可以看出签名就是把用户的密码 .用户名 和签名key生成一个md5串就可以了 刚好jmeter 有个md5 生成,生成前需要获取name ,password k ...
- 更新中国地区ip列表
鉴于高总的IPIP.net的数据库的准确性,推荐使用下列源: https://github.com/17mon/china_ip_list/blob/master/china_ip_list.txt ...
- 微信小程序:冒泡事件及其阻止
事件的类别分为几种: 点击事件:tap 长按事件:longtap 触摸事件:touchstart: touchend:touchcancel:touchmove 其他:input:submit.... ...
- MySql(十一):MySQL性能调优——常用存储引擎优化
一.前言 MySQL 提供的非常丰富的存储引擎种类供大家选择,有多种选择固然是好事,但是需要我们理解掌握的知识也会增加很多.本章将介绍最为常用的两种存储引擎进行针对性的优化建议. 二.MyISAM存储 ...
- Android log 日志分析
一. Log 日志中 Bug 类型 程序异常强制关闭: Force Close ,Fatal 程序无响应: Application Not Response , ANR(应用无响应).一般是主线程超时 ...
- Atitit 404错误的排查流程总结 v3 qaf
Atitit 404错误的排查流程总结 v3 qaf 1.1. 用了注解不生效 提示404 Not Found1 1.2. 路径不对了,开头多了个空格1 2. 500 Servlet Excepti ...
- 细说php(二) 变量和常量
一. 变量的声明 1. php中声明变量的方法: $var = 123; 2. php是弱类型的语言, 变量的类型由存储的值决定 注: Java是强类型语言, 声明变量一定要先指定类型 二. 变量的 ...
- python *和**的用法
1.使用场景 *和**用在函数参数列表中 2.*作函数参数 以列表的形式提供参数 def foo(*args): for arg in args: print(arg) foo(1, 2, 3) 运行 ...
- sql乘法函数实现方式
sql中有很多聚合函数,例如 COUNT.SUM.MIN 和 MAX. 但是唯独没有乘法函数,而很多朋友开发中缺需要用到这种函数,今天告诉大家一个不错的解决方案 logx+logy=logx*y 这是 ...