码迷,mamicode.com
首页 > 其他好文 > 详细

Permutations II

时间:2014-12-22 19:27:07      阅读:187      评论: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].

vector<vector<int> >& permute(vector<int> vecInt)
{
    vector<int> vecWorker;
    vector<vector<int> > vecPermu;
    vector<int> vecVisit(vecInt.size());

    sort(vecInt.begin(), vecInt.end());
    
    helper(vecPermu, vecWorker, vecInt, vecVisit);

    return vecPermu;
}

void helper(vector<vector<int> >& vecPermu, vector<int>& vecWorker, const vector<int>& vecInt, vector<int>& vecVisit)
{
    if (vecWorker.size() == vecInt.size())
    {
        vecPermu.push_back(vecWorker);
        return;
    }

    for (int i = 0; i < vecInt.size(); i++)
    {
        if (vecVisit[i] == 1 || (i != 0 && vecInt[i] == vecInt[i-1] && vecVisit[i-1] == 0))
        {
            continue;
        }

        vecVisit[i] = 1;
        vecWorker.push_back(vecInt[i];
        helper(vecPermu, vecWorker, vecInt);
        vecWorker.pop_back(vecInt[i]);
        vecVisit[i] = 0;
    }
}

 

Permutations II

标签:

原文地址:http://www.cnblogs.com/litao-tech/p/4178775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!