zoukankan      html  css  js  c++  java
  • 【leetcode】Permutations II (middle)

    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].

     
    思路:
    找规律递归 一个数跟自己后面的数字交换如 1 2 2 第一个数字和第2个数字换, 但是不换重复的数字 第一个数字和第三个数字就不换了
    class Solution {
    public:
        vector<vector<int> > permuteUnique(vector<int> &num) {
            vector<vector<int>> ans;
            if(num.empty())
                return ans;
    
            permute(ans,  num, 0);
            return ans;
        }
       //不知道为什么 注释掉的这种 在我自己的电脑上就ok 但是提交就总是Output Limit Exceeded??
    //void permute(vector<vector<int>> &ans, vector<int> num, int k) //{ // if(k >= num.size()) // { // ans.push_back(num); // return; // } // for(int j = k; j < num.size(); j++) //和自己或后面交换 // { // if (j > k && num[j] == num[j-1]) continue; //prevent duplicates // swap(num[k], num[j]); // permute(ans, num, k + 1); // swap(num[k], num[j]); // } //} void permute(vector<vector<int>> &ans, vector<int> num, int k) { if(k >= num.size()) { ans.push_back(num); return; } vector<int> hash; for(int j = k; j < num.size(); j++) //和自己或后面交换 { if(find(hash.begin(), hash.end(), num[j]) == hash.end()) { hash.push_back(num[j]); swap(num[k], num[j]); permute(ans, num, k + 1); swap(num[k], num[j]); } } } };
  • 相关阅读:
    jquery 读取 xml 属性等于某值的 方法
    jquery 定时器
    jquery div 滚动条 最底部
    ajax success 不能返回值解决方案 async:false
    wiki 使用说明
    thinkphp 二维码封装函数
    100本书 慢慢来读
    2013 来了
    jquery 解析 xml
    键盘按键 事件
  • 原文地址:https://www.cnblogs.com/dplearning/p/4240089.html
Copyright © 2011-2022 走看看