首页 > 其他 > 详细

Permutations

时间:2016-03-11 22:03:09      阅读:199      评论:0      收藏:0      [点我收藏+]

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 }

 

Permutations

原文:http://www.cnblogs.com/FLAGyuri/p/5267165.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!