其他分享
首页 > 其他分享> > leetcode46 - Permutations - medium

leetcode46 - Permutations - medium

作者:互联网

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
  Enumerate numbers for each position。一开始我们只有3个空空的slots,第一个slot里可以填1,2,3任意一个数,假如填了1,剩下两个slots只能从【2,3】里面选。所以考虑搞个set里面track对于当前slot还available的数,对于每个slot遍历所有数,挨个看看这个数用过没,没用过就加它顺便把它标成对之后unavailable,进行下一层。restore的时候,把当前slot清空,放回available里。 其实还可以直接就对nums进行操作来标记,用过的就从nums里删了就好了,最后nums空了就说明一个permutation组装好了。注意vector里insert和erase的用法是针对index的,而不是item本身,这里提前把数get出来,放回去的时候要用到。   一共n!个permutations   实现:
class Solution {
private:
    void dfs(vector<int>& nums, vector<vector<int>>& res, vector<int>& permutation, unordered_set<int>& available){
        if (permutation.size() == nums.size())
            res.push_back(permutation);
        else{
            for (int i=0; i<nums.size(); i++){
                if (available.find(nums[i]) != available.end()){
                    permutation.push_back(nums[i]);
                    available.erase(nums[i]);
                    dfs(nums, res, permutation, available);
                    permutation.pop_back();
                    available.insert(nums[i]);
                }
            }
        }
    }
    
public:
    vector<vector<int>> permute(vector<int>& nums) {
        
        vector<vector<int>> res;
        vector<int> permutation;
        unordered_set<int> available(nums.begin(), nums.end());
        dfs(nums, res, permutation, available);
        return res;
        
    }
};

 

优化:

class Solution {
private:
    void dfs(vector<int>& nums, vector<vector<int>>& res, vector<int>& permutation){
        if (nums.size() == 0)
            res.push_back(permutation);
        else{
            for (int i=0; i<nums.size(); i++){
                int choice = nums[i];
                permutation.push_back(choice);
                nums.erase(nums.begin()+i);
                dfs(nums, res, permutation);
                permutation.pop_back();
                nums.insert(nums.begin()+i, choice);
            }
        }
    }
    
public:
    vector<vector<int>> permute(vector<int>& nums) {
        
        vector<vector<int>> res;
        vector<int> permutation;
        dfs(nums, res, permutation);
        return res;
        
    }
};

 

标签:available,slot,medium,nums,res,Permutations,vector,permutation,leetcode46
来源: https://www.cnblogs.com/xuningwang/p/13456250.html