C++ Solution, 12ms


  • 5
    Z

    You can also view more solution on Github

    class Solution {
    public:
    	vector<vector<int>> permute(vector<int>& nums) {
    		vector<vector<int>> ans;
    		permute(ans, nums, 0);
    		return ans;
    	}
    	
    	void permute(vector<vector<int>>& ans, vector<int>& perm, int begin)
    	{
    		if (begin == perm.size()) {
    			ans.push_back(perm);
    			return;
    		}
    		
    		for (int i=begin; i<perm.size(); i++) {
    			if (i!=begin && perm[i] == perm[begin]) continue;
    			swap(perm[i], perm[begin]);
    			permute(ans, perm, begin+1);
    			swap(perm[i], perm[begin]);
    		}
    		
    	}
    };

  • 0
    W
    This post is deleted!

  • 0
    F

    one question..
    permute(ans, perm, begin+1);
    here why you write begin+1 instead of i+1, when will you decide use i+1 or begin+1, because I notice in combinate sum II it is used i+1


  • 0
    D

    The method is like you pick the ith element, move it to the front, and permute the rest elements, then put it back.
    It does not make sense just to permute the elements after the ith.


  • 0
    Y

    the if statement in the for loop seems to be unnecessary, since there is not duplicated numbers in the input.


  • 0
    F

    @zhaotianzju "swap(perm[i], perm[begin]);" is not really needed. It would work without it too.


Log in to reply
 

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