leetcode Permutations II

来源:互联网 发布:淘宝联盟网站推广位 编辑:程序博客网 时间:2024/05/27 20:50

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 {private:    bool nextPermutation(vector<int> &num){         int index, size = num.size(), swapIndex;         for(index = size - 2; index >= 0 && num[index] >= num[index + 1]; index--);         if(num[index] >= num[index + 1]){             return false;         }         for(swapIndex = size - 1; num[swapIndex] <= num[index]; swapIndex--);         swap(num[swapIndex], num[index]);         for(++index,--size; index<size; swap(num[index++], num[size--]));         return true;    }public:    vector<vector<int> > permuteUnique(vector<int> &num) {        vector<vector<int> > ans;        sort(num.begin(), num.end());        do{            ans.push_back(num);        }while(nextPermutation(num));        return ans;    }};


0 0
原创粉丝点击