46. Permutations java solutions

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Subscribe to see which companies asked this question

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         List<List<Integer>> ans = new ArrayList<List<Integer>>();
 4         DFS(ans,0,nums);
 5         return ans;
 6     }
 7     
 8     public void DFS(List<List<Integer>> ans, int k, int[] nums){
 9         if(k == nums.length){
10             List<Integer> list = new ArrayList<Integer>();
11             for(int n : nums) list.add(n);
12             ans.add(list);
13         }
14         
15         for(int i = k; i< nums.length; i++){
16             Swap(nums,k,i);
17             DFS(ans,k+1,nums);
18             Swap(nums,k,i);
19         }
20     }
21     
22     public void Swap(int[] num, int i, int j){
23         int tmp = num[i];
24         num[i] = num[j];
25         num[j] = tmp;
26     }
27 }

47. Permutations II java solutions

全排列就是从第一个数字起每个数分别与它后面的数字交换.

大神链接:

http://blog.csdn.net/happyaaaaaaaaaaa/article/details/51534048

原文地址:https://www.cnblogs.com/guoguolan/p/5619346.html