46. Permutations

题目:

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

 

Hide Tags
  Backtracking  

链接: http://leetcode.com/problems/permutations/

题解:

求数组的全排列。需要用到DFS和Backtracking。 原理是从0到数组长度N,每次对之前加入的元素进行回溯。 注意此解法假定输入数组之中没有重复元素。

Time Complexity - O(n!), Space Complexity - O(n)。

public class Solution {

    public ArrayList<ArrayList<Integer>> permute(int[] nums) {

        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

        if(nums == null || nums.length == 0)

            return result;

        Arrays.sort(nums);

        ArrayList<Integer> list = new ArrayList<Integer>();

        helper(result, list, nums);

        return result;

    }

    

    private void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] nums){

        if(list.size() == nums.length){                   //in this problem we assume no duplicate exists in input array

            result.add(new ArrayList<Integer>(list));

            return;

        }

        

        for(int i = 0; i < nums.length; i++){

            if(list.contains(nums[i]))

                continue;

            list.add(nums[i]);

            helper(result, list, nums);

            list.remove(list.size() - 1);

        }

    }

}

 

测试: 

Reference:

http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html 

你可能感兴趣的:(IO)