Leetcode 46. Full array (classic backtracking method)

Thursday, March 18, 2021, the weather is fine [Do not lament the past, do not waste the present, do not fear the future]


1. Introduction

46. ​​Full array
Insert picture description here

2. Problem solution (retrospecting Dafa)

2.1 Temporary array method

class Solution {
    
    
public:
    unordered_set<int> uset; // 利用哈希表判断元素是否遍历过了
    vector<vector<int>> res;
    vector<vector<int>> permute(vector<int>& nums) {
    
    
        vector<int> tmp; // 临时数组,存放每一个排列的结果
        dfs(nums,tmp,0);
        return res;
    }

    void dfs(vector<int>& nums, vector<int>& tmp, int n){
    
    
        // 终止条件,所有位都遍历完了
        if(n==nums.size()){
    
    
            res.push_back(tmp);
            return;
        }
        for(int num:nums){
    
    
            // 如果 num 还没有遍历
            if(uset.find(num)==uset.end()){
    
    
                // 加入哈希表和临时数组
                uset.insert(num);
                tmp.push_back(num);

                // 继续遍历下一位
                dfs(nums,tmp,n+1);

                // 遍历完之后记得还原,避免分支污染
                uset.erase(num);
                tmp.pop_back();
            }
        }
    }
};

This is the answer I wrote when I first did it, and it's easier to understand. Although it can be passed, it is more time-consuming than the official method (the exchange method below).

2.2 Exchange method

class Solution {
    
    
public:
    void backtrack(vector<vector<int>>& res, vector<int>& output, int first, int len){
    
    
        // 所有数都填完了
        if (first == len) {
    
    
            res.emplace_back(output);
            return;
        }
        for (int i = first; i < len; ++i) {
    
    
            // 动态维护数组
            swap(output[i], output[first]);
            // 继续递归填下一个数
            backtrack(res, output, first + 1, len);
            // 撤销操作
            swap(output[i], output[first]);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
    
    
        vector<vector<int> > res;
        backtrack(res, nums, 0, (int)nums.size());
        return res;
    }
};

The exchange method is also a standard method to solve the full arrangement problem. Although the code is simple, it takes a little effort to understand it.

The following picture helps to understand:
Insert picture description here

*Complexity analysis

Insert picture description here
The calculation of time complexity is more difficult to understand. You can refer to the following picture to understand:
Insert picture description here
add up the number of exchanges of each layer, you can get the total number of calls:
Insert picture description here
Then you can derive the above formula.


references

https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/

https://blog.csdn.net/u013905744/article/details/113779407

Guess you like

Origin blog.csdn.net/m0_37433111/article/details/114968607