美文网首页
46. Permutations

46. Permutations

作者: SummerDreamEve | 来源:发表于2018-04-23 00:55 被阅读0次

题目

Given a collection of distinct integers, return all possible permutations.

思路

使用backtracking


xxx.jpg

代码

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        backtrack(nums,res,list);
        return res;
            
    }
    public void backtrack(int[] nums,List<List<Integer>> res,List<Integer> templist){           
        if(templist.size() == nums.length){
            res.add(new ArrayList<Integer>(templist));
        }
        else{
            for(int i=0;i<nums.length;i++){
                if(!templist.contains(nums[i])){
                    templist.add(nums[i]);
                    backtrack(nums,res,templist);
                    templist.remove(templist.size()-1); 
                }
                    
            }
        }  
       
        
    } 
}

相关文章

网友评论

      本文标题:46. Permutations

      本文链接:https://www.haomeiwen.com/subject/ttzhlftx.html