首页 > 其他 > 详细

leetcode------Permutations

时间:2015-03-22 18:05:10      阅读:221      评论:0      收藏:0      [点我收藏+]
标题: 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         }

 

技术分享

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

具体看代码:

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------Permutations

原文:http://www.cnblogs.com/pkuYang/p/4357601.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!