Permutation

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

For example, [1,2,3] have the following permutations:

time complexity: o(n!)

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (nums == null || nums.length == 0) return result;
        int n = nums.length;
        List<Integer> list = new ArrayList<Integer>();
        helper(result, list, nums);
        return result;

    }
    public void helper(List<List<Integer>> result, List<Integer> list, int[] nums){
        if(list.size() == nums.length ){
            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);
        }
    }

results matching ""

    No results matching ""