Share my simple c++ solution non-recursion


  • 1
    K
    //like PermutationsI
    //swap the start-th number,continue when:
    //target value has been swapped or is equal to start-th
    class Solution {
    public:
    	vector<vector<int>> permuteUnique(vector<int>& nums) {
    		vector<vector<int>> res;
    		//sort(nums.begin(),nums.end());
    		res.push_back(nums);
    		vector<int> tmp;
    		for(int start=0;start<nums.size();start++){
    			for(int l=res.size()-1;l>=0;l--){
    				set<int> swapped;
    				for(int i=start+1;i<nums.size();i++){
    					if(res[l][i]==res[l][start]||!swapped.insert(res[l][i]).second)
    						continue;
    					tmp=res[l];
    					swap(tmp[start],tmp[i]);
    					res.push_back(tmp);
    				}
    			}
    		}
    		return res;
    	}
    };

Log in to reply
 

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