Permutations(46)

Permutations

Given a collection of distinct numbers, return all possible
permutations.code

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

思路: 典型的backtracking,注意list在递归的过程一直在变化,因此每次加入的list须要从新建立。result.add(new ArrayList<Integer>(list));rem

时间复杂度:O(n!)
空间复杂度:O(n)io

public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        helper(result, list, nums);
        return result;
    }
    private void helper(List<List<Integer>> result, List<Integer> list, int[] nums) {
        if (list.size() == nums.length) {
            if (!result.contains(list)) {
                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);
        }
    }
}
本站公众号
   欢迎关注本站公众号,获取更多信息