思路1:用n!次next_permutation()
next_permutation()的复杂度是O(n),所以应该不会越界,当到了排列最大值时返回false;
class Solution {
public:
bool next(vector<int>& nums);
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
int n = nums.size();
if (n == 1) {
ans.push_back(nums);
return ans;
}
sort(nums.begin(), nums.end());
do {
ans.push_back(nums);
}while (next(nums));
return ans;
}
};
bool Solution :: next(vector<int>& nums) {
int i = nums.size() - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i == -1) return false;
int j = nums.size() - 1;
while (nums[j] <= nums[i]) {
--j;
}
swap(nums[i], nums[j]);
reverse(nums.begin() + i + 1, nums.end());
return true;
}
思路2:用dfs进行全排列
易错点:记不清全排列的模板,写的时候容易忘记对flag的更新
//模板
if (!flag[i]) {
flag[i] = 1;
a[m] = i;
dfs(m + 1);
flag[i] = 0;
}
class Solution {
public:
void dfs(int index, vector<int>& each, vector<vector<int>> &ans, vector<int>& nums, vector<int> &flag);
vector<vector<int>> permute(vector<int>& nums) {
int n = nums.size();
vector<int> each(n);
vector<int> flag(n, 0);
vector<vector<int>> ans;
dfs(0, each, ans, nums, flag);
return ans;
}
};
void Solution :: dfs(int index, vector<int>& each, vector<vector<int>> &ans, vector<int>& nums, vector<int> &flag) {
if (index == nums.size()) {
ans.push_back(each);
return ;
}
for (int i = 0; i < nums.size(); ++i) {
if (!flag[i]) {
flag[i] = 1; //不要忘记对flag更新
each[index] = nums[i];
dfs(index + 1, each, ans, nums, flag);
flag[i] = 0; //不要忘记对flag更新
}
}
}