Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Given an array nums of distinct integers, return all the possible permutations . You can return the answer in any order (C++) . This is

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order (C++). This is Leetcode 46 (Permutations).

This is a solution that I have trouble understanding, I wrote comments with questions.

class Solution {

public:

vector> permute(vector& nums) {

//base case, why is it necessary?

if(nums.size() <= 1){

return {nums};

}

vector> result;

for(int i = 0; i < nums.size(); i++){

vector v(nums.begin(),nums.end());

v.erase(v.begin() + i);

auto res = permute(v); //Why does permute(v) work here if our function is inside permute? Since permute is a vector of a vector does that mean permute(v) will make res a vector of a vector only containing the current v value, (in which v is a value of nums where 1 element is removed)?

for(int j = 0; j < res.size(); j++){ //wouldn't res.size() always be of size 1?

vector vfirst = res[j]; //don't understand

vfirst.insert(vfirst.begin(),nums[i]); //vector_name.insert (position, val) // don't understand

result.push_back(vfirst); //places into last element of vector //don't understand

}

}

return result;

}

};

Also, what is the time complexity of this algorithm? Is it O(n!)?

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning ASP.NET 4.5 Databases

Authors: Sandeep Chanda, Damien Foggon

3rd Edition

1430243805, 978-1430243809

More Books

Students also viewed these Databases questions

Question

True or False. Parametric equations defining a curve are unique.

Answered: 1 week ago

Question

What are some of the possible scenes from our future?

Answered: 1 week ago

Question

1. What are your creative strengths?

Answered: 1 week ago