LeetCode 46.全排列 dfs递归套路版

给定一个没有重复数字的序列,返回其所有可能的全排列。

 

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

思路:在java代码里面

java版:

class Solution {
    public static List> ans = new ArrayList>();//存储总答案
   
    public static int[] path = new int[100];//小答案 
    
    public static boolean[] v = new boolean[100];//标记是否用过
    
    //dfs套路,输入里面一般都有index表示你输入到哪里了,可以指引你从哪里开始,什么时候结束
    public static void robot(int idx,int[] nums){
        //只要是递归第一行永远是边界条件判断,有时候会记录结果
        if (idx >= nums.length){
            //记录ans
            List tmp = new ArrayList();
            for (int i = 0 ; i < nums.length; i++){
                tmp.add(nums[path[i]]);
            }
            ans.add(tmp);
            return;
        }
        //全排列
        for (int i = 0;i< nums.length;i++){
            if (v[i] == false){            
                path[idx] = i;//记录数组的下标
                v[i] = true;
                robot(idx+ 1,nums); //递归一次,加一层[1,2,3]               
                v[i] = false;
            }

        }
    }
    
    public List> permute(int[] nums) {
        ans.clear();
        robot(0,nums);
        return ans;
    }
}
# class Solution:
#     def permute(self, nums):
#         """
#         :type nums: List[int]
#         :rtype: List[List[int]]
#         """
        
        
#         """
#         [a,b,c]的全排列== a+[b,c],b+[a,c],c +[a,b]的全排列
#         """
#         if len(nums) <= 1: 
#             return [nums]
        
#         ans = []
        
#         for i, num in enumerate(nums):            
#             n = nums[:i] + nums[i+1:]  # n是剩余数的list            
#             for y in self.permute(n):  # 直到函数有return,一个数的时候[nums],所以y是list                
#                 ans.append([num] + y)           
#         return ans
 
class Solution:
    
    def permuteHelper(self, nums, pos, res, lists, visited):
        if len(lists) == len(nums):
            res.append(lists[:])
            
        
        for i in range(len(nums)):
            if visited[i]:
                continue
            visited[i] = True
            lists.append(nums[i])
            self.permuteHelper(nums, i + 1, res, lists, visited)
            lists.remove(nums[i])
            visited[i] = False
        
        
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        res = []
        visited = [False] * len(nums)
        self.permuteHelper(nums, 0, res, [], visited)
        return res

 

你可能感兴趣的:(LeetCode 46.全排列 dfs递归套路版)