全排列问题偷鸡摸狗做法
用强大的(猥琐的)next_permutation
31. 下一个排列
class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(),nums.end());
}
};
46. 全排列
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
do{
res.push_back(nums);
}while(next_permutation(nums.begin(),nums.end()));
return res;
}
};
47. 全排列 II
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>>res;
do{
res.push_back(nums);
}while(next_permutation(nums.begin(),nums.end()));
return res;
}
};
60. 第k个排列
class Solution {
public:
string getPermutation(int n, int k) {
string s;
for(int i=1;i<=n;i++) s+=to_string(i);
do{
k--;
if(!k)break;
}while(next_permutation(s.begin(),s.end()));
return s;
}
};
网友评论