您的位置:首页 > 其它

[LeetCode] Permutations

2015-06-02 23:09 246 查看
Well, have you solved the nextPermutation problem? If so, your code can be used in this problem. The idea is fairly simple:

sort
nums
in ascending order, add it to
res
;

generate the next permutation of
nums
using
nextPermutation()
, and add it to
res
;

repeat 2 until the next permutation of
nums
returns to the sorted condition in 1.

The code is as follows.

A final note, the following code can be applied to the problem of Permutations II without any modification since the cases of duplicates have already been handled in
nextPermutation()
. If you want to learn more about
nextPermutation()
, please visit this solution.

bool nextPermutation(vector<int>& nums) {
int k = -1;
for (int i = nums.size() - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
k = i;
break;
}
}
if (k == -1) {
sort(nums.begin(), nums.end());
return false;
}
int l = -1;
for (int i = nums.size() - 1; i > k; i--) {
if (nums[i] > nums[k]) {
l = i;
break;
}
}
swap(nums[k], nums[l]);
reverse(nums.begin() + k + 1, nums.end());
return true;
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > res;
sort(nums.begin(), nums.end());
res.push_back(nums);
while (nextPermutation(nums))
res.push_back(nums);
return res;
}


Of course, you are supposed to use the backtracking idea. A simple code is as follows.

void permutate(vector<int> nums, int start, vector<vector<int> >& res) {
if (start == nums.size()) {
res.push_back(nums);
return;
}
for (int i = start; i < nums.size(); i++) {
swap(nums[i], nums[start]);
permutate(nums, start + 1, res);
}
}

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