您的位置:首页 > 产品设计 > UI/UE

2018.1.13 LeetCode 47. Permutations II 60. Permutation Sequence 【STL简单应用】

2018-01-13 15:50 344 查看

47. Permutations II

Description

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],

[2,1,1]

]

题意:打印全排列,但没有重复的

分析: 记录下上一个排列,简单判断即可

参考函数

class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int> > res;
sort(nums.begin(),nums.end());
int len = nums.size();
vector<int> temp(len);
for(int i = 0;i < len;i++) {
temp[i] = nums[i];
}
res.push_back(temp);
while (next_permutation(nums.begin(),nums.end())) {
bool flg = false;
for(int i = 0;i < len;i++) {
if(nums[i] != temp[i]) {
flg = true;
break;
}
}
if(false) continue;
for(int i = 0;i < len;i++) {
temp[i] = nums[i];
}
res.push_back(temp);
}
return res;
}
};


60. Permutation Sequence

Description

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,

We get the following sequence (ie, for n = 3):

“123”

“132”

“213”

“231”

“312”

“321”

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

题意: 打印全排列的第k个,要求为字符串类型的

分析: 直接枚举即可

参考函数

class Solution {
public:
string getPermutation(int n, int k) {
string res;
vector<int> a;
int t = 1;
for(int i = 1;i <= n;i++) {
a.push_back(i);
res += (char) ('0' + i);
}
if(t == k) return res;
res.clear();
while (next_permutation(a.begin(),a.end())) {
t++;
if(t == k) {
for(int i = 1;i <= n;i++) {
res += (char) ('0' + a[i-1]);
}
return res;
}
}

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