Revised C++ Solution from TransMatrix, 18 lines and 23 ms


  • 0
    K

    Re: A non-recursive C++ implementation with O(1) space cost

    My solution revised from TransMatrix with fewer code and faster speed.

    class Solution {
    public:
    	vector<vector<int> > permuteUnique(vector<int> &S) {
    	    vector<vector<int> > res;
    		sort(S.begin(), S.end());		
    		res.push_back(S);
    		int i, j;
    		while (true){
    			for (i=S.size()-1; i>0 && S[i-1] >= S[i]; --i);
    			if(i == 0)	break;
    			for (j=S.size()-1; j>i-1 && S[j] <= S[i-1]; --j);				
    			swap(S[i-1], S[j]);
    			reverse(S.begin()+i, S.end());
    			res.push_back(S);
    		}
    		return res;
        }
    
    };
    

  • 0
    K
    This post is deleted!

Log in to reply
 

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