51. 数字排列(含重复数字)

2019-10-16  本文已影响0人  蜜糖_7474

题目地址:https://www.acwing.com/problem/content/87/

AC代码

class Solution {
public:
    vector<vector<int>> res;
    vector<int> path;

    bool canSwap(vector<int>& v,int start ,int end){
        for(int i=start;i<end;++i) if(v[i]==v[end]) return false;
        return true;
    }

    void f(vector<int>& v,int start,int len){
        if(start==len){
            res.push_back(path);
            return;
        }
        
        for(int i=start;i<len;++i){
            if(canSwap(v,start,i)){
                path.push_back(v[i]);
                swap(v[i],v[start]);
                f(v,start+1,len);
                swap(v[i],v[start]);
                path.pop_back();
            }
        }
    }
    
    vector<vector<int>> permutation(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        f(nums,0,nums.size());
        return res;
    }
};

总结

题解参考讨论区

上一篇 下一篇

猜你喜欢

热点阅读