My C++ solution with recursion


  • 0
    C
    class Solution {
    public:
        int getPermutation(vector<vector<int>>&result, vector<int>& nums, vector<int>& temp, int *used, int len) {
            if(temp.size() == len) {
                result.push_back(temp);
                return 1;
            }
            else {
                for(int i = 0;i < len;i ++) {
                    if(0 == used[i]) {
                        used[i] = 1;
                        temp.push_back(nums[i]);
                        getPermutation(result, nums, temp, used, len);
                        temp.erase(temp.begin() + temp.size() - 1);
                        used[i] = 0;
                    }
                }
            }
            return 1;
        }
    
        vector<vector<int>> permute(vector<int>& nums) {
            int len = nums.size();
            vector<vector<int>>result;
            vector<int>temp;
            int *used = new int[len];
            memset(used, 0, sizeof(int) * len);
            
            getPermutation(result, nums, temp, used, len);
            
            return result;
        }
    };

Log in to reply
 

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