您的位置:首页 > 其它

Permutations II

2015-07-25 13:45 330 查看
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]
.

Solution:

class Solution {
public:
void dfs(vector<vector<int>> &res, vector<int> &p, vector<int> &nums)
{
if(nums.size() == 0)
{
res.push_back(p);
return ;
}
for(int i = 0; i < nums.size(); )
{
int index = nums[i];
int next = i + 1;
while(next < nums.size() && nums[next] == index) next++;
p.push_back(index);
nums.erase(nums.begin() + i);
dfs(res, p, nums);
nums.insert(nums.begin() + i, index);
p.pop_back();
i = next;
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> p;
dfs(res, p, nums);

return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: