力扣 题目46- 全排列+47-全排列 II
作者:互联网
题目
题解
46.
一看这个题目 发现和 力扣 题目31-- 下一个排列 类似 一个是找下一个 一个是找全部
那么我们把一开始nums进行排序从小到大 然后循环31题的题解 加入vector<vector<int>> res; 如果i为-1则退出 循环即可
47.同上
代码
46
1 #include<iostream> 2 #include<vector> 3 #include<map> 4 #include<algorithm> 5 using namespace std; 6 class Solution { 7 public: 8 vector<vector<int>> permute(vector<int>& nums) { 9 sort(nums.begin(), nums.end()); 10 vector<vector<int>> res; 11 //加个循环 12 while (true) 13 { 14 res.push_back(nums); 15 map<int, int>additional; 16 int i = nums.size() - 1; 17 for (; i > -1; i--) { 18 additional.insert(pair<int, int>(nums[i], i)); 19 if (i > 0 && nums[i] > nums[i - 1]) { 20 for (map<int, int>::iterator it = additional.begin(); it != additional.end(); it++) 21 { 22 if (nums[i - 1] < it->first) { 23 nums[it->second] = nums[i - 1]; 24 nums[i - 1] = it->first; 25 break; 26 } 27 } 28 break; 29 } 30 } 31 if (i > -1) { 32 sort(nums.begin() + i, nums.end()); 33 } 34 else { 35 break; 36 } 37 } 38 return res; 39 } 40 }; 41 int main() { 42 Solution sol; 43 vector<int> nums = { 1,2,3,4 }; 44 vector<vector<int>> res = sol.permute(nums); 45 for (int i = 0; i < res.size(); i++) { 46 for (int j = 0; j < res[i].size(); j++) { 47 cout << res[i][j]; 48 } 49 cout << endl; 50 } 51 52 }View Code
47.
1 #include<iostream> 2 #include<vector> 3 #include<map> 4 #include<algorithm> 5 using namespace std; 6 class Solution { 7 public: 8 vector<vector<int>> permuteUnique(vector<int>& nums) { 9 sort(nums.begin(), nums.end()); 10 vector<vector<int>> res; 11 //加个循环 12 while (true) 13 { 14 res.push_back(nums); 15 map<int, int>additional; 16 int i = nums.size() - 1; 17 for (; i > -1; i--) { 18 additional.insert(pair<int, int>(nums[i], i)); 19 if (i > 0 && nums[i] > nums[i - 1]) { 20 for (map<int, int>::iterator it = additional.begin(); it != additional.end(); it++) 21 { 22 if (nums[i - 1] < it->first) { 23 nums[it->second] = nums[i - 1]; 24 nums[i - 1] = it->first; 25 break; 26 } 27 } 28 break; 29 } 30 } 31 if (i > -1) { 32 sort(nums.begin() + i, nums.end()); 33 } 34 else { 35 break; 36 } 37 } 38 return res; 39 } 40 }; 41 int main() { 42 Solution sol; 43 vector<int> nums = { 1,2,3,4 }; 44 vector<vector<int>> res = sol.permuteUnique(nums); 45 for (int i = 0; i < res.size(); i++) { 46 for (int j = 0; j < res[i].size(); j++) { 47 cout << res[i][j]; 48 } 49 cout << endl; 50 } 51 52 }View Code
标签:break,排列,nums,46,res,II,int,vector,include 来源: https://www.cnblogs.com/zx469321142/p/16248078.html