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

46. Permutations

时间:2017-07-24 19:09:57      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:style   possible   tin   res   div   span   str   lis   访问   

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]
]

看结果什么时候输出, 看子集添加元素时的起始位置—pos 或i是否添加过 

从头访问的dfs经常要看看是否访问过, 也可以用Arraylist 或boolean visited[] 的容器存储index, 这样可以用在重复且从头开始遍历的dfs里面
if (list.contains(nums[i])) { continue; }
public List<List<Integer>> permute(int[] nums) {
        // write your code here
        
        // write your code herenums
        ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        if (nums.length == 0) {
            result.add(list);
            return result;
        }
        //题目要求每个答案要有序
        Arrays.sort(nums);
        helper(result, list, nums);
        return result;
        
    }
    private void helper (ArrayList<List<Integer>> result, ArrayList<Integer> list, int[] nums) {
        //加上判断看看什么时候需要添加到结果中
        if (list.size() == nums.length) {
        result.add(new ArrayList<Integer>(list));
        }
        for (int i = 0; i < nums.length; i++) {
            //画图得到必须要跟前一个节点的值不同并且不是第一次循环进入的点(不然会空指针异常, 或者同一层次(pos进入)的点,
        // 即同一个递归函数不能跟后面的值一样) //什么时候往子集里添加元素 if (list.contains(nums[i])) { continue; } //加上判断防止栈溢出,保证子集的元素不断加入 list.add(nums[i]); helper(result, list, nums); list.remove(list.size() - 1); // 回溯法的 应用 } } }

  

46. Permutations

标签:style   possible   tin   res   div   span   str   lis   访问   

原文地址:http://www.cnblogs.com/apanda009/p/7230046.html

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