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);
        }
    }
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息