[LeetCode] 47. Permutations II Permutations II (C++)


Source of topic: https://leetcode-cn.com/problems/permutations-ii/

Title description

Given a sequence nums that can contain repeated numbers, return all non-repeated permutations in any order.

Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1 ,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3 ,2,1]]

提示:
1 <= nums.length <= 8
-10 <= nums[i] <= 10

General idea

  • This question is similar to https://leetcode-cn.com/problems/permutations/ . The problem-solving method is the backtracking method, but this question requires a pruning operation on the backtracking method
  • For example 1, if the whole arrangement can be repeated, there will be 3! situations, but because there is a repeated element 1, the repeated element is excluded from the arrangement, if the current element nums[i] is the same as the previous element nums[i-1] is repeated, and the previous element is already in the arrangement (used[i-1]==true), so the recursive stack of this element is returned to the parent node of the current element (node) to be arranged, and then The parent recursive stack loops i++, and then takes the following elements into consideration

Introduction to Backtracking

  • Backtracking is an algorithmic idea, and recursion is a programming method. Backtracking can be implemented by recursion.
  • The overall idea of ​​the backtracking method is: search every path, and each backtracking is for a specific path. To search the unexplored area under the current search path, there may be two situations:
class Solution {
    
    
public:
    vector<vector<int>> ret;
    vector<int> ans;
    vector<bool> used;
    int n;
    vector<vector<int>> permuteUnique(vector<int>& nums) {
    
    
        n = nums.size();
        used.assign(n, false);
        sort(nums.begin(), nums.end());
        dfs(nums, 0);
        return ret;
    }
    void dfs(vector<int>& nums, int depth){
    
    
        if(depth == n){
    
    
            ret.push_back(ans);
            return;
        }
        for(int i = 0 ; i < n ; ++i){
    
    
            if(!used[i]){
    
    
                if(!ans.empty() && i - 1 >= 0 && nums[i - 1] == nums[i] && used[i - 1] == true)
                    return;
                used[i] = true;
                ans.push_back(nums[i]);
                dfs(nums, depth + 1);
                used[i] = false;
                ans.pop_back();
            }

        }
    }
};

Complexity analysis

  • Time complexity: O(n*2^n). n is the length of the array, there are 2^n cases in total, and it takes O(n) time to create
  • Space complexity: O(n). The recursive stack space is (n)

Guess you like

Origin blog.csdn.net/lr_shadow/article/details/114521077