关闭

#16 Permutations II

标签: lintcoderecursion
50人阅读 评论(0) 收藏 举报
分类:

题目描述:

Given a list of numbers with duplicate number in it. Find all uniquepermutations.

Example

For numbers [1,2,2] the unique permutations are:

[
  [1,2,2],
  [2,1,2],
  [2,2,1]
]
题目思路:

这题和#15差不多。为了避免重复的情况,增加一个set去记录已经写入答案中的vector就好了。

Mycode(AC = 290ms):

class Solution {
public:
    /**
     * @param nums: A list of integers.
     * @return: A list of unique permutations.
     */
    vector<vector<int> > permuteUnique(vector<int> &nums) {
        // write your code here
        vector<vector<int>> ans;
        if (nums.size() == 0) return ans;
        
        vector<int> sofar;
        unordered_set<int> visited;
        set<vector<int>> answered;
        permute(ans, sofar, nums, visited, answered);
        return ans;
    }
    
    void permute(vector<vector<int>>& ans,
                 vector<int>& sofar,
                 vector<int>& nums,
                 unordered_set<int>& visited,
                 set<vector<int>>& answered)
    {
        if (sofar.size() == nums.size()) {
            if (answered.find(sofar) == answered.end()) {
                answered.insert(sofar);
                ans.push_back(sofar);
            }
            return;
        }
        
        for (int i = 0; i < nums.size(); i++) {
            if (visited.find(i) == visited.end()) {
                sofar.push_back(nums[i]);
                visited.insert(i);

                permute(ans, sofar, nums, visited, answered);
                
                sofar.pop_back();
                visited.erase(i);
            }
        }
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11981次
    • 积分:2241
    • 等级:
    • 排名:第16791名
    • 原创:221篇
    • 转载:1篇
    • 译文:0篇
    • 评论:10条
    文章分类
    文章存档