I have an accepted recursive solution, but I don't know how to convert it to an iterative solution using similar idea.


  • 0
    S

    Anyone can help me convert the following solution to iterative solution using the same idea?

    vector<vector<int> > subsets(vector<int> &S) {
        vector<vector<int>> result;
        vector<int> curResult;
        sort(S.begin(),S.end());
    
        findSubsets(S,result,curResult,0);
        return result;
    }
    
    void findSubsets(vector<int>&s, vector<vector<int>>& result, vector<int>& curResult, int startIndex){
        if(startIndex==s.size()){
            result.push_back(curResult);
            return;
        }
        
        //for each number, there are two possibilities
        //1:it is in the final subset
        curResult.push_back(s[startIndex]);
        findSubsets(s,result,curResult,startIndex+1);
        curResult.pop_back();
        
         //2:it is not in the final subset
        findSubsets(s,result,curResult,startIndex+1);
    }

Log in to reply
 

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