代码随想录算法训练营第二十九天| 491.递增子序列、46.全排列、47.全排列 II

代码随想录算法训练营第二十九天| 491.递增子序列、46.全排列、47.全排列 II

  • 491.递增子序列
  • 46.全排列
  • 47.全排列 II

491.递增子序列

题目链接
文章讲解

class Solution {
public:
    vector<int> path;
    vector<vector<int>> ans;

    void backtracking(const vector<int>& nums, int start) {
        if (path.size() >= 2) 
            ans.push_back(path);
        int used[201] = {0};
        for (int i = start; i < nums.size(); i++) {
            if (used[nums[i] + 100]) continue;
            used[nums[i] + 100] = 1;
            if (path.empty() || nums[i] >= path.back()) {
                path.push_back(nums[i]);
                backtracking(nums, i + 1);
                path.pop_back();
            }
        }
    }

    vector<vector<int>> findSubsequences(vector<int>& nums) {
        backtracking(nums, 0);
        return ans;
    }
};

46.全排列

题目链接
文章讲解

class Solution {
public:
    vector<int> path;
    vector<vector<int>> ans;
    bool used[6] = {0};

    void backtracking(const vector<int>& nums, bool used[]) {
        if (path.size() == nums.size()) {
            ans.push_back(path);
            return;
        }
        for (int i = 0; i < nums.size(); i++) {
            if (used[i]) continue;
            path.push_back(nums[i]);
            used[i] = true;
            backtracking(nums, used);
            used[i] = false;
            path.pop_back();
        }
    }

    vector<vector<int>> permute(vector<int>& nums) {
        backtracking(nums, used);
        return ans;
    }
};

47.全排列 II

题目链接
文章讲解

class Solution {
public:
    vector<int> path;
    vector<vector<int>> ans;
    bool used[8] = {0};

    void backtracking(const vector<int>& nums, bool used[]) {
        if (path.size() == nums.size()) {
            ans.push_back(path);
            return;
        }
        for (int i = 0; i < nums.size(); i++) {
            if (used[i]) continue;
            if (i > 0 && !used[i - 1] && nums[i] == nums[i - 1]) continue;
            path.push_back(nums[i]);
            used[i] = true;
            backtracking(nums, used);
            used[i] = false;
            path.pop_back();
        }
    }

    vector<vector<int>> permuteUnique(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        backtracking(nums, used);
        return ans;
    }
};

你可能感兴趣的:(算法)