题解 | #没有重复项数字的全排列#

没有重复项数字的全排列

http://www.nowcoder.com/practice/4bcf3081067a4d028f95acee3ddcd2b1

import java.util.*;

public class Solution {
    ArrayList<ArrayList<Integer>> ans ;
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        ans = new ArrayList<>();
        //将数组转化为集合
        ArrayList<Integer> list = new ArrayList<>();
        for(int i = 0;i<num.length;i++){
            list.add(num[i]);
        }
      
        callBack(list,0,new ArrayList<>());
        return ans;
    }
    //回溯
    public void callBack(ArrayList<Integer> list,int index ,ArrayList<Integer> path){
        //最后一个下标时加入路径集合,加入到结果集合中
        if(index == list.size()-1){
            path.add(list.get(index));
            ans.add(new ArrayList<>(path));
            path.remove(list.get(index));
            return;
        }
        //遍历
        for(int i = index;i<list.size();i++){
            Collections.swap(list,index,i);
            path.add(list.get(index));
            callBack(list,index+1,path);
            path.remove(list.get(index));
            Collections.swap(list,index,i);
        }
    }
    
}
全部评论

相关推荐

06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务