文章目录
- 1. 题目信息
- 2. 解题
1. 题目信息
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:输入: [1,1,2]
输出:
[[1,1,2],[1,2,1],[2,1,1]
]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/permutations-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
在leetcode46的基础上做修改
类似题目:
LeetCode 491. 递增子序列(回溯+判重)
LeetCode 996. 正方形数组的数目(回溯+剪枝)
- 先对数组排序
- 如果前一个数等于后一个数,且前者没有访问过,
nums[i-1] == nums[i] && ! visited[i-1]
,则直接跳过
class Solution {
public:vector<vector<int>> permuteUnique(vector<int>& nums) {vector<int> row;vector<vector<int>> ans;bool occurred[nums.size()];memset(occurred, 0, sizeof(bool)*nums.size());sort(nums.begin(), nums.end());bt(nums, 0, occurred, row, ans);return ans;}void bt(vector<int>& nums, int count, bool *occurred, vector<int> row, vector<vector<int>>& ans){if(count == nums.size()){ans.push_back(row); return;}for(int i = 0; i < nums.size(); ++i){if(occurred[i] == false){if(i >= 1 && nums[i-1] == nums[i] && !occurred[i-1])continue; //搜索剪枝occurred[i] = true;row.push_back(nums[i]);bt(nums,count+1,occurred,row,ans);row.pop_back();occurred[i] = false;}}}
};
class Solution:def permuteUnique(self, nums: List[int]) -> List[List[int]]:import itertoolsreturn list(set(itertools.permutations(nums, len(nums))))
44 ms 15.2 MB Python3