完全な配列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);

       }      

  }

}

おすすめ

転載: www.cnblogs.com/fightingcode/p/10992066.html