46. Permutations

---恢复内容开始---

题目链接:https://leetcode.com/problems/permutations/

解题思路:

!!!所有的全排列,都用这种交换的思想做得了!!!不要贪多,会一个就行。记住他

然后所有的深度优先搜索都按照那个套路来,也不要贪多,背熟,他妈的。

 1 import java.util.ArrayList;
 2 class Solution {
 3     public List<List<Integer>> permute(int[] nums) {
 4         
 5         List<List<Integer>> res  = new ArrayList<>();
 6         
 7         if(nums==null||nums.length==0)
 8             return res;
 9         Arrays.sort(nums);
10         helper(res,nums,0);
11         return res;
12     }
13     
14     public void helper(List<List<Integer>> res,int []nums,int i)
15     {
16         if(i==nums.length-1)
17         {
18             List<Integer> list = new ArrayList<>();
19             for (int num : nums) list.add(num);
20             if(!res.contains(list))
21             {
22                 
23                 res.add(list);
24             }
25         }
26         
27         else
28         {
29             for(int j=i;j<nums.length;j++)
30             {
31                 swap(nums,i,j);
32                 helper(res,nums,i+1);
33                 swap(nums,j,i);
34             }
35         }
36     }
37     
38     public void swap(int []nums,int i,int j)
39     {
40         if(i!=j)
41         {
42             int item = nums[i];
43             nums[i]=nums[j];
44             nums[j] =item;
45         }
46     }
47 }
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10940421.html