代码随想录算法训练营第二十四天| 491.递增子序列 46.全排列 47.全排列 II
491.递增子序列
此题的难点:
1,前提需要保留原有顺序
2,保证递增
3,保证去重
注意:
去重一定要有set的同时保证有顺序
代码:
1 void findSubsequences_trackBack(vector<int>& nums, int startIndex, vector<int>& path, vector<vector<int>>& result) 2 { 3 if (path.size() >= 2 ) 4 { 5 result.push_back(path); 6 } 7 8 unordered_set<int> selected; 9 for (int i = startIndex; i < nums.size(); i++) 10 { 11 if (selected.find(nums[i]) != selected.end() || (path.size() > 0 && nums[i] < path.back())) 12 { 13 continue; 14 } 15 selected.insert(nums[i]); 16 path.push_back(nums[i]); 17 findSubsequences_trackBack(nums, i + 1, path, result); 18 path.pop_back(); 19 } 20 21 } 22 vector<vector<int>> findSubsequences(vector<int>& nums) { 23 vector<vector<int>> result; 24 if (nums.size() == 0) return result; 25 26 vector<int>path; 27 findSubsequences_trackBack(nums, 0, path, result); 28 return result; 29 }
46.全排列
思路:
从0开始,只不过需要删掉已经遍历过的节点
疑问:
我是用unorderedset的时候出现了重复的输出,但是我并没有,需要确认
代码:
1 void permute_trackBack(vector<int>& nums,vector<bool>&used, vector<int>& path,vector<vector<int>>& result) 2 { 3 if (path.size() == nums.size()) 4 { 5 result.push_back(path); 6 return; 7 } 8 9 //如何解决 多个i从0开始? 10 for (int i = 0; i < nums.size(); i++) 11 { 12 if (used[i]) 13 continue; 14 15 used[i] = true; 16 path.push_back(nums[i]); 17 permute_trackBack(nums,used, path, result); 18 used[i] = false; 19 path.pop_back(); 20 } 21 } 22 23 vector<vector<int>> permute(vector<int>& nums) { 24 vector<vector<int>> result; 25 if (nums.size() == 0) return result; 26 27 vector<bool> used(nums.size(),false); 28 vector<int> path; 29 permute_trackBack(nums, used, path, result); 30 31 return result; 32 }
47.全排列 II
思路:
对层进行去重
代码:
1 void permuteUnique_trackBack(vector<int>& nums, vector<bool>& used, vector<int>& path, vector<vector<int>>& result) 2 { 3 if (path.size() == nums.size()) 4 { 5 result.push_back(path); 6 return; 7 } 8 9 set<int> selected; 10 for (int i = 0; i < nums.size(); i++) 11 { 12 if (selected.find(nums[i]) != selected.end() || used[i]) 13 continue; 14 15 used[i] = true; 16 selected.insert(nums[i]); 17 path.push_back(nums[i]); 18 permuteUnique_trackBack(nums, used, path, result); 19 used[i] = false; 20 path.pop_back(); 21 } 22 23 } 24 vector<vector<int>> permuteUnique(vector<int>& nums) { 25 vector<vector<int>> result; 26 if (nums.size() == 0) return result; 27 vector<bool>used(nums.size(), false); 28 vector<int> path; 29 permuteUnique_trackBack(nums, used, path, result); 30 31 return result; 32 }