zoukankan      html  css  js  c++  java
  • leetcode-46-全排列

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

    示例:

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

    Java实现:

    class Solution {
    
        /*
    
       time complexity: O(n!)  space complexity : O(n)
    
       时间复杂度不懂的看这: https://www.1point3acres.com/bbs/thread-117602-1-1.html
    
       递归法解本题  
    
       */
    
    
       public List<List<Integer>> permute(int[] nums) {
    
           List<List<Integer>> res = new ArrayList<>();
    
           //边界条件判断
    
           if(nums == null || nums.length == 0) return res;
    
           helper(res, new ArrayList<>(), nums);
    
           return res;
    
       }
    
       
    
       //辅助函数  res, list, nums数组
    
       public static void helper(List<List<Integer>> res, List<Integer> list, int[] nums){
    
           //res添加list
    
           if(list.size() == nums.length){
    
               res.add(new ArrayList<>(list));
    
               return ;
    
           }
    
           for(int i = 0; i < nums.length ; i++){
    
               //ArrayList 的list中是否包含nums的当前元素
    
               if(list.contains(nums[i])) continue;  //O(n)
    
               //否则看看下一个是否满足要求
    
               list.add(nums[i]);
    
               helper(res, list, nums);
    
               list.remove(list.size() - 1);
    
           }      
    
      }
    
    }
    
  • 相关阅读:
    053705
    053704
    053703
    053702
    053701
    053700
    053699
    053698
    053697
    HDU 3746 Cyclic Nacklace
  • 原文地址:https://www.cnblogs.com/fightingcode/p/10992066.html
Copyright © 2011-2022 走看看