Problem: 46. 全排列
解析
回溯算法 bitset
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: vector<vector<int>> permute(vector<int> &nums) { bitset<10> numsStatus; vector<int> resPart; vector<vector<int>> res; backtrack(nums, numsStatus, resPart, res); return res; } void backtrack(vector<int> &nums, bitset<10> &numsStatus, vector<int> &resPart, vector<vector<int>> &res) { if (resPart.size() == nums.size()) { res.emplace_back(resPart); return; } for (int i = 0; i < nums.size(); ++i) { if (numsStatus[i] == false) { resPart.emplace_back(nums[i]); numsStatus[i] = true; backtrack(nums, numsStatus, resPart, res); resPart.pop_back(); numsStatus[i] = false; } } } };
|
字典序法
比如614532,它的nextPermutation生成过程如下:
614532 ->
找到最右侧上升点4 ->
从右到左找到第一个大于4的点5 ->
交换两点 ->
615432 ->
反转5右侧 ->
615234
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public: vector<vector<int>> permute(vector<int> &nums) { vector<vector<int>> res; sort(nums.begin(), nums.end()); do { res.emplace_back(nums); } while (nextPermutation(nums)); return res; } bool nextPermutation(vector<int> &nums) { int n = nums.size();
int changePoint = n - 2; while (changePoint >= 0 && nums[changePoint] > nums[changePoint + 1]) { --changePoint; } if (changePoint < 0) { return false; }
int changePointBigger = n - 1; while (changePointBigger >= 0 && nums[changePointBigger] <= nums[changePoint]) { --changePointBigger; } swap(nums[changePoint], nums[changePointBigger]); reverse(nums.begin() + changePoint + 1, nums.end()); return true; } };
|