昨天笔试做了一个题,需要全排列;
可惜我连全排列都不会,深深感受到了自己的菜;
决定将力扣的两道全排列深入探究下;
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题是最经典的全排序;而且可以很好地帮助我们理解回溯,用数学排列组合的方式很容易,但是记住我们用数学方法也不是乱排,运用分类思想;
第一类:1打头
第二类:2打头
第三类:3打头
讲解
这篇讲解很好,大家可以看看;
我们可以再细化一下:
全排列【1,2,3】=
1 【剩余数字的全排列】
2 【剩余数字的全排列】
3 【剩余数字的全排列】
这种问题都可以用递归解决,回溯也是递归的一种;但回溯的特点是什么回退,回到过去;
看一幅图就很好理解为什么回退;
当1 2 3得到之后,需要回到1继续算,这就是回退,具体操作就是状态还原,不还原状态谈何回退、
这个图还像什么,dfs深度优先遍历,dfs算法将回溯算法体现的淋漓尽致,这个算法是尽可能的搜索树的分支,当节点v的所在边都已被探寻过,搜索将回溯到发现节点v的那条边的起始节点。这个过程一直进行到已经发现从源节点可达的所有节点为止。
很多路径问题都用到dfs
再来看看回溯算法
算法分析与设计中这样介绍回溯的,所有的递归都可以用树来表示,这就是空间结构;
全排列代码:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Permute {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> lists=new LinkedList<>();
if(nums==null){
return lists;
}
int len=nums.length;
boolean[] isR=new boolean[len];
LinkedList<Integer> list=new LinkedList<>();
dfs(0,nums,len,list,isR,lists);
return lists;
}
public static void dfs(int depth,int []nums,int len,LinkedList<Integer> list,boolean[]isR,List<List<Integer>> lists){
if(depth==len){
lists.add(new ArrayList<>(list));
return;
}
for(int i=0;i<len;i++){
if(!isR[i]){
list.addLast(nums[i]);
isR[i]=true;
System.out.println(" 递归之前==="+list);
dfs(depth+1,nums,len,list,isR,lists);
isR[i]=false;
list.removeLast();
System.out.println(" 递归之后==="+list);
}
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
Permute permute = new Permute();
List<List<Integer>> lists = permute.permute(nums);
System.out.println(lists);
}
}
理解一个算法的关键就是进行一步一步调试
递归之前===[1]
递归之前===[1, 2]
递归之前===[1, 2, 3]
递归之后===[1, 2]
递归之后===[1]
递归之前===[1, 3]
递归之前===[1, 3, 2]
递归之后===[1, 3]
递归之后===[1]
递归之后===[]
递归之前===[2]
递归之前===[2, 1]
递归之前===[2, 1, 3]
递归之后===[2, 1]
递归之后===[2]
递归之前===[2, 3]
递归之前===[2, 3, 1]
递归之后===[2, 3]
递归之后===[2]
递归之后===[]
递归之前===[3]
递归之前===[3, 1]
递归之前===[3, 1, 2]
递归之后===[3, 1]
递归之后===[3]
递归之前===[3, 2]
递归之前===[3, 2, 1]
递归之后===[3, 2]
递归之后===[3]
递归之后===[]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
第一次调试的时候我发现每次都回退两步,是什么变量决定的呢?
其实仔细一想也不难,因为只有回退两步才有重排列的可能,因为一个数的排列就是它本身,而且为了各种可能都涉及到,应该先回退两步而不是两步以上;
代码中是:
i=0:list.add(1){1}
isR[0]=true;
dfs(1)---i=0(isR[0]=true),i++
i=1:list.add(2){1,2}
isR[1]=true;
dfs(2)---i=0;i++;
i=1;i++;
i=2:list.add(3)
isR[2]=true;
dfs(3)----return i=2:isR[2]=false;
list.remove(3){1,2}----此时继续进入for循环;i++=3,这一层for循环结束
---i=1:isR[1]=false;
list.remove(2){1}---此时for循环可以进去
可以从调试看出,它回退两步是由for循环的下标和bool数组控制的,当每一次i严格控制了当前数字,bool数组确保不会重复;
全排列2
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
第一个想到就是在原代码的基础上加上set就好;
然而并没有实现去重,然后发现set中对集合去重没有像基本元素那么简单,需要重写比较器;
那么显然行不通了,
方框圈起的是重复的,有什么特点呢?
1 和前面的1相等;
2 和前面的2相等;
所以我们就可以加上判断,如果相等直接continue;
if(i>0&&isR[i-1]==false&&nums[i-1]==nums[i]){
continue;
}
我们继续思考,这样的条件随便一个数组就可行吗,因为我们是i-1和i比较,所以必须先排序,这样就不会出现bug了;
这里必须是false,说明前一个元素有可能重新排列,才有可能出现重复;
import java.util.*;
public class Permute2 {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> lists=new LinkedList<>();
if(nums==null){
return lists;
}
int len=nums.length;
boolean[] isR=new boolean[len];
//HashSet<LinkedList<Integer>> set=new HashSet<>();
LinkedList<Integer> list=new LinkedList<>();
Arrays.sort(nums);
dfs(0,nums,len,list,isR,lists);
return lists;
}
public static void dfs(int depth,int []nums,int len,LinkedList<Integer> list,boolean[]isR,List<List<Integer>> lists){
if(depth==len){
//set.add(list);
lists.add(new ArrayList<>(list));
return;
}
for(int i=0;i<len;i++){
if(!isR[i]){
if(i>0&&isR[i-1]==false&&nums[i-1]==nums[i]){
continue;
}
list.addLast(nums[i]);
isR[i]=true;
System.out.println(" 递归之前==="+list);
dfs(depth+1,nums,len,list,isR,lists);
isR[i]=false;
list.removeLast();
System.out.println(" 递归之后==="+list);
}
}
}
public static void main(String[] args) {
int[] nums = {1, 1, 3};
Permute2 permute = new Permute2();
List<List<Integer>> lists = permute.permuteUnique(nums);
System.out.println(lists);
}
}
旅行者售货员也是经典的回溯法的应用
class Graph1
{
int n ;
int []x; // 当前解
int cc;
int []bestx; //
int bestc; //
int [][]a;
public void Swap_Ar(int []br,int i, int j)
{
int tmp =br[i];
br[i] = br[j];
br[j] = tmp;
}
public Graph1()
{
n =0;
x = null;
cc = 0;
bestx = null;
bestc = 0x7fffffff;
a = null;
}
public void Init_Graph()
{
n = 4;
x = new int[n+1];
for(int i = 0;i<=n;++i)
{
x[i] = i;
// 0 1 2 3 4
// 0 //1 2 3 4
}
cc = 0;
bestx = new int[n+1];
bestc = 0x7fffffff;
a = new int[n+1][n+1];
int arcnum = 6;
int []begin={1, 1, 1, 2, 2, 3};
int []end ={2, 3, 4, 3, 4, 4};
int []cost ={30,6, 4, 5, 10,20};
for(int i = 0;i<n+1;++i)
{
for(int j = 0;j<n+1;++j)
{
a[i][j] = 0x7fffffff;
}
}
for(int i = 0;i<=n;++i) a[i][i] = 0;
for(int i = 0;i<arcnum;++i)
{
a[begin[i]][end[i]] = cost[i];
a[end[i]][begin[i]]= cost[i];
}
}
public void BackTrack(int i)
{
if(i == n)
{
if(a[x[i-1]][x[i]] < Integer.MAX_VALUE && a[x[i]][x[1]] < Integer.MAX_VALUE
&& (bestc == Integer.MAX_VALUE || cc + a[x[i-1]][x[i]] + a[x[i]][x[1]] < bestc))
{
bestc = cc + a[x[i-1]][x[i]] + a[x[i]][x[1]];
for(int j = 0;j<= n;++j)
{
bestx[j] = x[j];
}
}
}
else
{
for(int j = i;j<=n;++j)
{
if(a[x[i-1]][x[i]] < Integer.MAX_VALUE &&
(bestc == Integer.MAX_VALUE || cc + a[x[i-1]][x[i]] < bestc ))
{
Swap_Ar(x,j,i);
cc+= a[x[i-1]][x[i]];
BackTrack(i+1);
cc-= a[x[i-1]][x[i]];
Swap_Ar(x,j,i);
}
}
}
}
public int Tsp()
{
BackTrack(2);
return bestc;
}
public void Path()
{
for(int i = 1;i<=n;++i)
{
System.out.printf("%d ",bestx[i]);
}
System.out.println(bestx[1]);
}
public static void main(String[] args) {
int []arr={1,2,3,4};
Graph1 myG=new Graph1() ;
myG .Init_Graph() ;
int sum=myG .Tsp() ;
System.out.println(sum );
myG .Path() ;
}
}