# leetcode 随笔 Permutations,Permutations II

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

[1,2]和[2,1] 然后有三个位置插入 ，插入3 变成

[3,1,2] [1,3,2] [1,2,3] [3,2,1] [2,3,1] [2,1,3]

class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
if (nums.empty()) return res;
vector<int> t; t.push_back(nums[0]);
res.push_back(t);
for (int i = 1; i < nums.size(); i++)
{
vector<vector<int>> tmp;
for (int j = 0; j < res.size(); j++)
{
vector<int> kk = res[j];
for (int t = 0; t <= i; t++)
{
kk.insert(kk.begin() + t, nums[i]);
tmp.push_back(kk);
kk.erase(kk.begin() + t);
}
}
res = tmp;
}
return res;
}
};

=================================================

=================================================

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> res;
if (nums.empty()) return res;
vector<int> t; t.push_back(nums[0]);
res.push_back(t);
for (int i = 1; i < nums.size(); i++)
{
vector<vector<int>> tmp;
for (int j = 0; j < res.size(); j++)
{
vector<int> kk = res[j];
for (int t = 0; t <= i; t++)
{
if (t < i&&nums[i] != kk[t])
{
kk.insert(kk.begin() + t, nums[i]);
tmp.push_back(kk);
kk.erase(kk.begin() + t);
}
else if (t == i)
{
kk.insert(kk.begin() + t, nums[i]);
tmp.push_back(kk);
kk.erase(kk.begin() + t);
}
}
}
res = tmp;
for (int i = 0; i < res.size(); i++)
{
for (int k = i + 1; k < res.size(); k++)
{
if (res[i] == res[k])
res.erase(res.begin() + k);
}
}
}
return res;
}
};

class Solution {
public:
void recursion(vector<int> nums, int i, vector<vector<int> > &res) {
if (i == nums.size()-1) {
res.push_back(nums);
return;
}
for (int k = i; k < nums.size(); k++) {
if (i != k && nums[i] == nums[k]) continue;
swap(nums[i], nums[k]);
recursion(nums, i+1, res);
}
}

vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
recursion(nums,0,res);
return res;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120