首页 > 其他 > 详细

[LintCode] Permutations II

时间:2015-05-24 01:19:11      阅读:168      评论:0      收藏:0      [点我收藏+]

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

class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> paths;
        if (nums.empty()) {
            return paths;
        }
        
        vector<int> index;
        vector<int> path;
        permuteUniqueHelper(nums, index, path, paths);
        return paths;
        
    }
    
private:
    void permuteUniqueHelper(const vector<int> &nums,
                             vector<int> &index,
                             vector<int> &path,
                             vector<vector<int>> &paths) {
        if (path.size() == nums.size()) {
            paths.push_back(path);
            return;
        }
        
        // 保证相同的数不在同一位置出现两次以上
        unordered_set<int> hashset;
        for (int ix = 0; ix < nums.size(); ix++) {
            if (find(index.begin(), index.end(), ix) == index.end() && hashset.count(nums[ix]) == 0) {
                hashset.insert(nums[ix]);
                
                index.push_back(ix);
                path.push_back(nums[ix]);
                permuteUniqueHelper(nums, index, path, paths);
                index.pop_back();
                path.pop_back();
            }
        } 
    }
};

[LintCode] Permutations II

原文:http://www.cnblogs.com/jianxinzhou/p/4525222.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!