47. 全排列 Ii

47. 全排列 II #

链接 #

47. 全排列 II

题目 #

给定一个可包含重复数字的序列 nums按任意顺序 返回所有不重复的全排列。

示例 1:

输入:nums = [1,1,2]
输出:
[[1,1,2],
 [1,2,1],
 [2,1,1]]

示例 2:

输入:nums = [1,2,3]
输出:[[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

解答 #

class Solution {
 public:
  void permuteUniqueImpl(vector<vector<int>>& ret,
                         std::vector<int>& nums,
                         std::vector<int>& history,
                         int n,
                         int start,
                         std::vector<bool>& used) {
    if (start == n) {
      ret.push_back(history);
      return;
    }

    for (int i = 0; i < n; ++i) {
      if (used[i]) {
        continue;
      }
      if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
        continue;
      }
      history.push_back(nums[i]);
      used[i] = true;
      permuteUniqueImpl(ret, nums, history, n, start + 1, used);
      used[i] = false;
      history.pop_back();
    }
  }
  vector<vector<int>> permuteUnique(vector<int>& nums) {
    int n = static_cast<int>(nums.size());
    sort(nums.begin(), nums.end());
    std::vector<bool> used(n, false);
    vector<vector<int>> ret;
    std::vector<int> history;
    int start = 0;
    permuteUniqueImpl(ret, nums, history, n, start, used);
    return ret;
  }
};
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        def backtrack(path, used):
            if len(path) == len(nums):
                result.append(path[:])
                return
            for i in range(len(nums)):
                if used[i] or (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]):
                    continue
                used[i] = True
                path.append(nums[i])
                backtrack(path, used)
                path.pop()
                used[i] = False
        
        nums.sort()
        result = []
        used = [False] * len(nums)
        backtrack([], used)
        return result