My stl and dfs cpp solutions


  • -1
    C

    STL:

    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) 
        {
            std::sort(nums.begin(), nums.end());
            
            vector< vector<int> > result;
            result.push_back(nums);
            
            vector<int> p(nums);
            while( std::next_permutation(p.begin(), p.end()) )
                result.push_back( vector<int>(p) );
                
            return result;
        }
    };
    

    DFS:
    class Solution {
    public:
    vector< vector<int> > result;

    bool isValid(const vector<int> &res, int n, int pos)
    {
        for(int i=0; i < pos; i++)
            if(res[i] == n) return false;
            
        return true;
    }
    
    void dfs(const vector<int>& nums, vector<int>& res, int depth)
    {
        for(int n : nums)
        {
            if( !isValid(res, n, depth) ) continue;
            
            res[depth] = n;
            
            if(depth == nums.size()-1)
            {
                result.push_back( vector<int>(res) );
                return;
            }
            
            dfs(nums, res, depth+1);
        }
    }
    
    vector<vector<int>> permute(vector<int>& nums) 
    {
        std::sort(nums.begin(), nums.end());
        
        vector<int> res( nums.size() );
        dfs(nums, res, 0);
            
        return result;
    }
    

    };


Log in to reply
 

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