leetcode------Permutations

标题: Permutations
通过率: 31.7%
难度: 中等

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].

本题就是数字的全排列,dfs的递归,

1、【2,3】中进行交换一次【3、2】然后加上【1】

2、【1,2】交换一次【2,1】然后【1,3】交换一次的加上2

3、再第二的基础上交换【2,3】,然后【1,2】交换一次加上3

####################

遍历排序树的算法:(就是这样做不知道为什么)

1         for(int j=start;j<num.length;j++){

2             swap(num,j,start);

3             dfs(res,num,start+1);

4             swap(num,j,start);

5         }

 

leetcode------Permutations

########################

具体看代码:

public class Solution {

    public ArrayList<ArrayList<Integer>> permute(int[] num) {

        ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();

        dfs(res,num,0);

        return res;

        

    }

    public void dfs(ArrayList<ArrayList<Integer>> res,int[] num,int start){

        if(start==num.length){

            ArrayList<Integer> tmp=new ArrayList<Integer>();

            for(int i=0;i<num.length;i++){

                tmp.add(num[i]);

            }

            if(!res.contains(tmp))

                res.add(tmp);

        }

        for(int j=start;j<num.length;j++){

            swap(num,j,start);

            dfs(res,num,start+1);

            swap(num,j,start);

        }

    }

    public void swap(int []num,int a,int b){

        int tmp=num[a];

        num[a]=num[b];

        num[b]=tmp;

    }

}

 

你可能感兴趣的:(LeetCode)