码迷,mamicode.com
首页 > 其他好文 > 详细

Permutations 解答

时间:2015-10-16 11:27:32      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

Question

Given a collection of 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].

Solution

Traditional backtracking  way to solve this problem.

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         Arrays.sort(nums);
 4         int length = nums.length;
 5         List<List<Integer>> result = new ArrayList<List<Integer>>();
 6         boolean[] visited = new boolean[length];
 7         
 8         dfs(nums, visited, new ArrayList<Integer>(), result);
 9         return result;
10     }
11     
12     private void dfs(int[] nums, boolean[] visited, List<Integer> record, List<List<Integer>> result) {
13         if (record.size() == nums.length) {
14             if (!result.contains(record))
15                 result.add(new ArrayList<Integer>(record));
16             return;
17         }
18         for (int i = 0; i < nums.length; i++) {
19             if (!visited[i]) {
20                 record.add(nums[i]);
21                 visited[i] = true;
22                 dfs(nums, visited, record, result);
23                 // Restore
24                 record.remove(record.size() - 1);
25                 visited[i] = false;
26             }
27         }
28     }
29 }

 

Permutations 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4884556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!