Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

recursion - permutation in C++

class Solution {
public:
     vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int> > result;
        vector<int> sofar;
        permutehelper(nums, sofar, result);
        return result;
    }
    
    void permutehelper(vector<int> &rest, vector<int> &sofar, vector<vector<int>> &ans){
                
        if(rest.size() == 0) {
            ans.push_back(sofar);
        }
        else{
            for(int i = 0; i < rest.size(); i++){
                sofar.push_back(rest[i]);
                rest.erase(rest.begin() + i);
                permutehelper(rest, sofar, ans);
            }
        }
    }
};    

How do I modify it to return all permutation, Currently it is giving only [[1,2,3]]. I know there are many solutions but I want to make it work using vectors sofar and rest.

question from:https://stackoverflow.com/questions/65713644/permutation-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only have one rest vector (and only one sofar vector) because you are passing by reference. That means that when you remove an element from rest, it's gone. You never put it back, so it's gone forever. (In fact, you're removing elements from the vector passed as an argument to permute. Some would say that modifying the argument is poor interface design.)

You probably want to pass the parameter vectors by value (other than ans, which accumulates results and thus should be permanently modified). Of course, passing by value makes copies, which introduces an unnecessary quadratic complexity, but it will allow the algorithm to work as expected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...