Share my C++ solution,easy to understand


  • 0
    V
    class Solution {
    public:
        vector<vector<int>> permuteUnique(vector<int>& nums) {
            vector<vector<int>> ret;
            vector<int> temp;
            int n = nums.size();
            
            permute_help(nums, 0, n, temp, ret);
            
            return ret;
        }
        
        void permute_help(vector<int>& nums, int start, int end, vector<int> temp, vector<vector<int>> &ret)
        {
            if (start == end)
            {
                ret.push_back(temp);
                return;
            }
            
            int i = 0;
            int j = 0;
            bool permute_break = false;
            int t = 0;
            
            for (i = start; i < end; i++)
            {
                permute_break = false;
                for (j = start; j < i; j++)
                {
                    if (nums[j] == nums[i])
                    {
                        permute_break = true;
                        break;
                    }
                }
                
                if (permute_break)
                    continue;
                
                t = nums[start];
                nums[start] = nums[i];
                nums[i] = t;
                
                temp.push_back(nums[start]);
                permute_help(nums, start + 1, end, temp, ret);
                temp.pop_back();
                
                t = nums[start];
                nums[start] = nums[i];
                nums[i] = t;
            }
        }
    };

  • 0
    V

    Compare with the problem "Permutations",just add the following:

    permute_break = false;
    for (j = start; j < i; j++)
    {
            if (nums[j] == nums[i])
            {
                    permute_break = true;
                    break;
            }
     }
                
    if (permute_break)
            continue;

Log in to reply
 

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