1. 程式人生 > >LeetCode-----46.Permutations&&47.Permutations II (全排列----回溯法)

LeetCode-----46.Permutations&&47.Permutations II (全排列----回溯法)

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],
  [2,1,1]
]

Subscribe to see which companies asked this question

重複元素和不重複元素

思路:包含重複元素,保證重複元素出現的前後順序不變即可

class Solution {
    /**
     * @param nums: A list of integers.
     * @return: A list of unique permutations.
     */
    public List<List<Integer>> permuteUnique(int[] nums) {
    
        ArrayList<List<Integer>> results = new ArrayList<List<Integer>>();
    
        if (nums == null) {
            return results;
        }
    
        if(nums.length == 0) {
            results.add(new ArrayList<Integer>());
            return results;
        }

        Arrays.sort(nums);
        ArrayList<Integer> list = new ArrayList<Integer>();
        int[] visited = new int[nums.length];
        for ( int i = 0; i < visited.length; i++){
            visited[i] = 0;
        }
     
        helper(results, list, visited, nums);    
        return results;
    }
    
    
    public void helper(ArrayList<List<Integer>> results, 
                   ArrayList<Integer> list, int[] visited, int[] nums) {
        
        if(list.size() == nums.length) {
            results.add(new ArrayList<Integer>(list));
            return;
        }
        
        for(int i = 0; i < nums.length; i++) {
            if ( visited[i] == 1 || ( i != 0 && nums[i] == nums[i - 1]
            && visited[i-1] == 0)){
                continue;
            }
            /*
            上面的判斷主要是為了去除重複元素影響。
            比如,給出一個排好序的陣列,[1,2,2],那麼第一個2和第二2如果在結果中互換位置,
            我們也認為是同一種方案,所以我們強制要求相同的數字,原來排在前面的,在結果
            當中也應該排在前面,這樣就保證了唯一性。所以當前面的2還沒有使用的時候,就
            不應該讓後面的2使用。
            */
            visited[i] = 1;
            list.add(nums[i]);
            helper(results, list, visited, nums);
            list.remove(list.size() - 1);
            visited[i] = 0;
        }
     } 
}