zoukankan      html  css  js  c++  java
  • leetcode47. Permutations II

    leetcode47. Permutations II

    题意:

    给定可能包含重复的数字的集合,返回所有可能的唯一排列。

    思路:

    这题全排列两种写法。

    • 用hash表记录已经visit的数字,虽然看起来很朴实,但是比另一种方法稳多了,而且hash表的查找也是很高效的。
    • 另一种用swap进行交换,确保已经遍历的点在前面,未遍历的点在后面。这个方法在没有duplicate的情况下,比如上一题,看不出有什么坑点。有了duplicate之后感觉很鸡儿皮。 首先要用sort排序,不然的话还是会遍历到重复的点的。每次寻找下一个点的时候还要用sort排一次序,因为每次经过排序之后,用两个swap已经无法还原了,一定要再次排序。 用swap的话特别注意[0,0,0,1,9]这个样例,让我感觉swap坑点有点fly。

    ac代码:

    swap方法

    C++

    class Solution {
    public:
        vector<vector<int>>res;
        vector<vector<int>> permuteUnique(vector<int>& nums) {
            res.clear();
            vector<int> temp;
            
            dfs(nums,temp,0);
            return res;
        }
        
        void dfs(vector<int>& nums,vector<int> temp, int begin)
        {
            if(begin >= nums.size())
            {
                res.push_back(temp);
                return;
            }
            sort(nums.begin() + begin,nums.end());
            for(int i = begin; i < nums.size(); i++)
            {
                temp.push_back(nums[i]);
                swap(nums[i], nums[begin]);
                dfs(nums,temp,begin + 1);
                temp.pop_back();
                //swap(nums[i], nums[begin]);
                sort(nums.begin() + begin,nums.end());
                while(i + 1 < nums.size() && nums[i + 1] == nums[i]) i++;
            }
        }
        
        
    };
    

    python

    
    
  • 相关阅读:
    组合模式扩展,有选择的递归
    SQL分页查询【转】
    facade外观模式
    C#:几种数据库的大数据批量插入 faib
    装饰模式的扩展
    yeild之我理解
    数据库操作 sqlserver查询存储过程+分页
    SQL Server 索引结构及其使用(二)[转]
    SQL索引使用初步,(转)
    解决多集成,多子类,扩展等 装饰模式
  • 原文地址:https://www.cnblogs.com/weedboy/p/7226750.html
Copyright © 2011-2022 走看看