本文主要是介绍算法训练营第29天|LeetCode 491.递增子序列 46.全排列 47.全排列Ⅱ,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
LeetCode 491.递增子序列
题目链接:
LeetCode 491.递增子序列
解题思路:
用哈希集合进行去重,同一树层不能取重复元素。
代码:
class Solution {
public:vector<vector<int>>result;vector<int>path;void backtracking(vector<int>&nums,int startIndex){if(path.size()>1){result.push_back(path);}unordered_set<int>uset;for(int i=startIndex;i<nums.size();i++){if((!path.empty() && nums[i] < path.back())||uset.count(nums[i])){continue;}uset.insert(nums[i]);path.push_back(nums[i]);backtracking(nums,i+1);path.pop_back(); }}vector<vector<int>> findSubsequences(vector<int>& nums) {backtracking(nums,0);return result;}
};
LeetCode 46.全排列
题目链接:
LeetCode 46.全排列
解题思路:
用used布尔数组记录当前元素是否用过,进入迭代时,就能保住当前元素不被用两次。
代码:
class Solution {
public:vector<vector<int>>result;vector<int>path;void backtracking(vector<int>&nums,vector<bool>used){if(path.size()==nums.size()){result.push_back(path);return;}for(int i=0;i<nums.size();i++){if(used[i]==true) continue;used[i] = true;path.push_back(nums[i]);backtracking(nums,used);path.pop_back();used[i] = false;}}vector<vector<int>> permute(vector<int>& nums) {vector<bool>used(nums.size(),false);backtracking(nums,used);return result;}
};
LeetCode 47.全排列Ⅱ
题目链接:
LeetCode 47.全排列Ⅱ
代码:
class Solution {
public:vector<int>path;vector<vector<int>>result;void backtracking(vector<int>&nums,vector<bool>used){if (path.size() == nums.size()) {result.push_back(path);return;}for (int i = 0; i < nums.size(); i++){if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {continue;}if (used[i] == false) {used[i] = true;path.push_back(nums[i]);backtracking(nums, used);path.pop_back();used[i] = false;}}}vector<vector<int>> permuteUnique(vector<int>& nums) {result.clear();path.clear();sort(nums.begin(), nums.end()); // 排序vector<bool> used(nums.size(), false);backtracking(nums, used);return result;}
};
这篇关于算法训练营第29天|LeetCode 491.递增子序列 46.全排列 47.全排列Ⅱ的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!