Permutations(46)

Permutations 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], an

Permutations

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

思路: 典型的backtracking,注意list在递归的过程一直在变化,所以每次加入的list需要重新创建。result.add(new ArrayList(list));

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

public class Solution {
    public List> permute(int[] nums) {
        List> result = new ArrayList>();
        List list = new ArrayList();
        helper(result, list, nums);
        return result;
    }
    private void helper(List> result, List list, int[] nums) {
        if (list.size() == nums.length) {
            if (!result.contains(list)) {
                result.add(new ArrayList(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);
        }
    }
}

关键字:list, nums, result, arraylist