算法训练营第29天|LeetCode 491.递增子序列 46.全排列 47.全排列Ⅱ

LeetCode 491.递增子序列

题目链接:

LeetCode 491.递增子序列

解题思路:

用哈希集合进行去重,同一树层不能取重复元素。

代码:

class Solution {
public:
    vector>result;
    vectorpath;
    void backtracking(vector&nums,int startIndex){
        if(path.size()>1){
            result.push_back(path);
        }
        unordered_setuset;
        
        for(int i=startIndex;i> findSubsequences(vector& nums) {
        backtracking(nums,0);
        return result;
    }
};

LeetCode 46.全排列

题目链接:

LeetCode 46.全排列

解题思路:

用used布尔数组记录当前元素是否用过,进入迭代时,就能保住当前元素不被用两次。

代码:

class Solution {
public:
    vector>result;
    vectorpath;
    void backtracking(vector&nums,vectorused){
        if(path.size()==nums.size()){
            result.push_back(path);
            return;
        }
        for(int i=0;i> permute(vector& nums) {
        vectorused(nums.size(),false);
        backtracking(nums,used);
        return result;
    }
};

LeetCode 47.全排列Ⅱ

题目链接:

LeetCode 47.全排列Ⅱ

代码:

class Solution {
public:
    vectorpath;
    vector>result;
    void backtracking(vector&nums,vectorused){
        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> permuteUnique(vector& nums) {
        result.clear();
        path.clear();
        sort(nums.begin(), nums.end()); // 排序
        vector used(nums.size(), false);
        backtracking(nums, used);
        return result;
    }
};

你可能感兴趣的:(算法,leetcode,职场和发展)