I suppose I should not use next_permutation()


  • 0
    P

    recursive way

    typedef vector<int>vi;
    vector<vi> generate(vi a,int m){
        vector<vi> per;
        if(m==1) {
            per.push_back(vi{a[0]});
            return per;
        }
        for(int j=m-1;j>=0;j--){
            if(j!=m-1) swap(a[j],a[m-1]);
            vector<vi> tmp = generate(a,m-1);
            for(vi vec:tmp){
                vec.push_back(a[m-1]);
                per.push_back(vec);
            }
        }
        return per;
    }
    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            vi tmp = nums;
            return generate(tmp,tmp.size());
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.