Permutations

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], and [3,2,1].

考察深度优先搜索DFS。(DFS 要点:1.递归 2.回溯)

list 用于存放一个可能的排列方案。

result 保存所有排序。

思路:1.遍历数组如果该数值不在list中则将该数加入到list中,如果存在则跳过该数(注意:题意是没有重复的数)。

   2.当列表的长度等于数组的长度时,表明找到了一个排列方案将lis添加到result中。

 

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         List<List<Integer>> ans = new ArrayList<>();
 4         if (nums == null || nums.length == 0) {
 5             return ans;
 6         }
 7         List<Integer> list = new ArrayList<>();
 8         helper(ans, list, nums);
 9         return ans;
10         
11     }
12     private void helper(List<List<Integer>> ans, List<Integer>list, int[] nums) {
13         if (list.size() == nums.length) {
14             ans.add(new ArrayList<Integer>(list));
15             return;
16         }
17         for (int i = 0; i < nums.length; i++) {
18             if (list.contains(nums[i])) {
19                 continue;
20             }
21             list.add(nums[i]);
22             helper(ans, list, nums);
23             list.remove(list.size() -1);
24         }
25         
26     }
27 }

 

posted @ 2016-03-11 20:39  YuriFLAG  阅读(229)  评论(0)    收藏  举报