c++ solution by using recursion


  • 0
    S
    class Solution {
    public:
    	vector<vector<int>> permute(vector<int>& nums) {
    		vector<vector<int>>resu;
    		vector<vector<int>>resu_temp;
    		if (nums.size() == 1)
    		{
    			resu.push_back(nums);
    			return resu;
    		}
    		else
    		{
    			int num_last = nums[nums.size() - 1];
    			nums.pop_back();
    			resu = permute(nums);
    			for (auto it = resu.begin(); it != resu.end(); it++)
    			{
    				for (auto it2 = it->begin(); it2 != it->end();it2++)
    				{
    					auto it2_new = it->insert(it2, num_last);
    					resu_temp.push_back(*it);
    					it2 = it->erase(it2_new);
    				}
    				it->push_back(num_last);
    				resu_temp.push_back(*it);
    			
    			}
    			resu = resu_temp;
    			return resu;
    		}
    
    	}
    };
    

Log in to reply
 

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