您的位置:首页 > 编程语言 > C语言/C++

leetcode 日经贴,Cpp code -Permutations II

2015-05-06 14:43 351 查看
Permutations II

class Solution {
public:
bool next_permutation(vector<int> &nums) {
int n = nums.size();
if (n <= 1) {
return false;
}
int ed = n - 1;
while (ed > 0 && nums[ed - 1] >= nums[ed]) {
--ed;
}
int st = ed;
if (ed > 0) {
for (int i = n - 1; i >= 0; --i) {
if (nums[i] > nums[ed - 1]) {
ed = i;
break;
}
}
swap(nums[ed], nums[st - 1]);
}
ed = n - 1;
bool ret = st > 0;
while (st < ed) {
swap(nums[st++], nums[ed--]);
}
return ret;
}

vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int> >ret;
ret.push_back(nums);
while (next_permutation(nums)) {
ret.push_back(nums);
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: