LeetCode:全排列【46】

LeetCode:全排列【46】

题目描述

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

示例:

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

题目分析

  首先题目给了一个没有重复数字的序列,它的全排列也一定不含重复数字。我们采用回溯框架法快速解题。

  我们就简单思考一个问题,每个排列的第一个元素是如何生成的!

  

  我们从左往右,首先我们将1加入tmpList(临时存储排列的线性表)中,此后再由它开始产生第二个、第三个数字,最后生成排列存储在结果中。我们再将1作为第一个元素开始处理后,赶紧把他删了,再将2加入到tmpList中,此后再有它开始产生第二个、第三个数字,最后生成排列存储在结果中....

  也就是说处理第i个位置的元素时,就要考虑到i位置的所有取值,我们在处理为1的元素后,赶紧把他删了处理为2的元素.....这样第i个位置就有所有的情况了。

  我觉得这一段讲的并不是特别清楚,我只是在讲某一层的元素要如何处理,该层要考虑所有元素,就在处理后某个元素后,再把该层腾空,让给其他元素。

Java题解

public List<List<Integer>> permute(int[] nums) {
   List<List<Integer>> list = new ArrayList<>();
   // Arrays.sort(nums); // not necessary
   backtrack(list, new ArrayList<>(), nums);
   return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
   if(tempList.size() == nums.length){
      list.add(new ArrayList<>(tempList));
   } else{
      for(int i = 0; i < nums.length; i++){ 
         if(tempList.contains(nums[i])) continue; // element already exists, skip
         tempList.add(nums[i]);
         backtrack(list, tempList, nums);
         tempList.remove(tempList.size() - 1);
      }
   }
} 

猜你喜欢

转载自www.cnblogs.com/MrSaver/p/9934852.html