Permutations
题目
- Given a collection of distinct numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
- 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]
]
分析
1. 题目要求
题目1和题目2都是要求出给定数组的全排列,区别在于一个有重复的数字而一个没有重复的数字。
2. 求解思路
这两道题可以用相同的方法求解。
对给出的数组进行升序排序。
使用c++自带的 nexpermutation函数 依次求出下一个排列。
nexpermutation函数原型如下:
#include <algorithm>
bool next_permutation(iterator start, iterator end);
如果想要自己写出求解下一个排列的函数,可参照我之前写的 Next Permutation 。
3. 代码如下
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
do {
result.push_back(nums);
} while(next_permutation(nums.begin(), nums.end()));
return result;
}
};
还没有评论,来说两句吧...