Permutations

来源:互联网 发布:太阳光谱数据在哪有 编辑:程序博客网 时间:2024/06/11 00:37

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

public class Solution {    public List<List<Integer>> permute(int[] nums) {        Arrays.sort(nums);        List<List<Integer>> ret = new ArrayList<List<Integer>>();        List<Integer> list = new ArrayList<Integer>();        boolean[] used = new boolean[nums.length];        helper(ret,list,nums,used);        return ret;    }        private void helper(List<List<Integer>> ret,List<Integer> list,int[] nums, boolean[] used) {        if (list.size() == nums.length) {            ret.add(new ArrayList<Integer>(list));            return;        }                for (int i = 0; i < nums.length; i++) {            if (used[i]))                continue;                        list.add(nums[i]);            used[i] = true;            helper(ret, list, nums, used);            list.remove(list.size() - 1);            used[i] = false;        }    }}

Permutations 2

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].


use a boolean array to store the status of the elements. If the current element equals the previous one and the previous element has not been visited before, skip current element. for example, if current element is the second 1, it will cause duplicate [1,1,2] and [1,2,1], so we need to skip it.

public class Solution {    public List<List<Integer>> permuteUnique(int[] nums) {        Arrays.sort(nums);        List<List<Integer>> ret = new ArrayList<List<Integer>>();        List<Integer> list = new ArrayList<Integer>();        boolean[] visited = new boolean[nums.length];        helper(ret,list,nums,visited);        return ret;    }        private void helper(List<List<Integer>> ret, List<Integer> list, int[] nums, boolean[] visited) {        if (list.size() == nums.length) {            ret.add(new ArrayList<Integer>(list));            return;        }                for (int i = 0; i < nums.length; i++) {            if (visited[i] || i != 0 && nums[i] == nums[i - 1] && !visited[i - 1])                continue;                        visited[i] = true;            list.add(nums[i]);            helper(ret,list,nums,visited);            list.remove(list.size() - 1);            visited[i] = false;        }    }}




0 0
原创粉丝点击