zoukankan      html  css  js  c++  java
  • Permutations I&&II

    Permutations I

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

    For example,
    [1,2,3] have the following permutations:
    [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

    这里需要特别注意,第15行用的是index+1,而不是i+1这里也是与以前的代码思路不一样的地方,开始就是这里用了i+1,导致测试一直不通过,试了很久才发现这个错误。

    class Solution {
     private:
         vector<vector<int>> res;
     public:
         void getPer(vector<int>&nums,int index,int lenth)
         {
             if(index==lenth)
                 res.push_back(nums);
             int temp;
             for(int i=index;i<lenth;i++)
             {
                 temp=nums[i];
                 nums[i]=nums[index];
                 nums[index]=temp;
                 getPer(nums,index+1,lenth);
                 temp= nums[i];
                 nums[i]=nums[index];
                 nums[index]=temp;
             }
             return ;
         }
         vector<vector<int>> permute(vector<int>& nums) {
             getPer(nums,0,nums.size());
             return res;
             
        }
     };

    Permutations II

    Given a collection of numbers that might contain duplicates, return all possible unique permutations.

    For example,
    [1,1,2] have the following unique permutations:
    [1,1,2], [1,2,1], and [2,1,1].

    这道题其实也纠结了我很久。没想到只需要定义一个set来存储已经交换过的元素值就可以把问题完美的解决了。

    class Solution {
    public:
        vector<vector<int> > permuteUnique(vector<int> &num) {
            if(num.size() <= 0) return res;
            permCore(num, 0);
            return res;
        }
    private:
        vector<vector<int> > res;
        void permCore(vector<int> &num, int st){
            if(st == num.size()) res.push_back(num);
            else{
                set<int> swp;
                for(int i = st; i < num.size(); ++i){
                    if(swp.find(num[i]) != swp.end()) continue;
                    swp.insert(num[i]);
                    swap(num, st, i);
                    permCore(num, st+1);
                    swap(num, st, i);
                }
            }
        }
        
        void swap(vector<int> &num, int left, int right){
            int tmp = num[left];
            num[left] = num[right];
            num[right] = tmp;
        }
    };
  • 相关阅读:
    golang 简易聊天
    golang 自定义封包协议(转的)
    PHP 7 测试用例(转)
    android 百度地图开发
    Android studio 签名使用转
    百度ueditor 拖文件或world 里面复制粘贴图片到编辑中 上传到第三方问题
    Android控件属性大全(转)
    Android studio 一个项目中添加两个module遇到的bug
    win7 64位DCOM配置(关于导出excel 配置计算机组件服务)(转)
    Python学习--07迭代器、生成器
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4533748.html
Copyright © 2011-2022 走看看