My simple C++ solution DFS run 4ms~ beat 88%


  • 0
    K
    
    class Solution {
    public:
        vector<vector<int>> subsets(vector<int>& nums) {
            vector<vector<int>>out;
            vector<int> tmp;
            out.push_back(tmp);
            if(nums.empty())
                return out;
            sort(nums.begin(),nums.end());
            DFS_nums(out,nums,tmp,nums.size(),0);
            return out;
        }
        
        void DFS_nums(vector<vector<int>> &out,vector<int> &nums, vector<int> &tmp, int k , int begin)
        {
            if(!k)
                ;
            else
            {
                int i,tmp_num = INT_MAX;
                for(i = begin ; i < nums.size() ; i++)
                {
                    if(nums[i] != tmp_num)//这是判断是否重复
                    {
                        tmp_num = nums[i] ; // 上一个有效的数字
                        tmp.push_back(nums[i]);
                        out.push_back(tmp); //这里写
                        DFS_nums(out,nums,tmp,k-1,i+1);
                        tmp.pop_back();
                    }
                }
            }
        }
        
        
    };
    

Log in to reply
 

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