My recursive solution,20ms


  • 0
    N
    class Solution {
    public:
    	vector<vector<int>> permute(vector<int>& nums) {
    		vector<vector<int>> res, tmp;
    		vector<int> tn;
    		if (nums.size() < 1) return res;
    		if (nums.size() == 1)
    		{
    			res.push_back(nums);
    			return res;
    		}
    		if (nums.size() == 2)
    		{
    			res.push_back(nums);
    			swap(nums[0], nums[1]);
    			res.push_back(nums);
    			return res;
    		}
    		//size>2
    		for (int i = 0; i < nums.size(); i++)
    		{
    			int reserved = nums[i];
    			tn = nums;
    			swap(tn[i], tn[nums.size() - 1]);
    			tn.pop_back();
    			tmp = permute(tn);
    			for (int j = 0; j < tmp.size(); j++)
    			{
    				tmp[j].push_back(reserved);
    				res.push_back(tmp[j]);
    			}
    		}
    		return res;
    	}
    };

Log in to reply
 

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