2016年7月20日星期三

[LeetCode] #47 Permutations II


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


没有评论:

发表评论