简体   繁体   中英

C++ Using Vector as Key in Set/Map is not resulting in Unique Answers

I am working on a Leetcode question and tired making a set with vector as the key. However, it fails in making sure that there are no duplicates in my results. I also tried using a Map, but failed to even print its values as I believe I don't have any idea about how we can print values of map containing vector of int as the key. Please let me know what am I doing wrong in my code and why is it not working. Also, how to print whole vector keys using maps.

My code is as follows:

class Solution 
{
   public:
      vector<vector<int>> permuteUnique(vector<int>& nums) 
      {

         vector<vector<int>>result;
         permutations(nums,0,result);

         return result; 

      }

      void permutations(vector<int>&nums, int l, vector<vector<int>>&result)
      {
         set<vector<int>>s;
         if(l>=nums.size())
         {
            if(s.find(nums)==s.end())
            {
               s.insert(nums);
               result.push_back(nums);
               return;
            }

            else if(s.find(nums)!=s.end())
               return;
         }

         for(int i=l;i<nums.size();i++)
         {
            swap(nums[l],nums[i]);
            permutations(nums,l+1,result);
            swap(nums[l],nums[i]);
         }
      }
};

Your assumption is wrong - the std::set< std::vector<int> > does a 'full' comparison of the contents of the vectors. So using as key shouldn't give you the key errors that you suspect - it is just as good as a std::set< std::string > if you are familiar with std::string . Link to documentation: https://en.cppreference.com/w/cpp/container/vector/operator_cmp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM