046. Permutations

Difficulty: 

Frequency: 

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].


My solution:
Data structure:
Steps:
Complexity:
Runtime:
Space:
Test cases:
Corner cases:
Code:
class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> results;
        vector<int> tmp_vec;
        permute_helper(nums, results, tmp_vec);
        return results;
    }
    void permute_helper(vector<int> nums, vector<vector<int>> &results, vector<int> tmp_vec) {
        if (nums.empty()) {
            results.push_back(tmp_vec);
            return;
        }
        for (int i = 0; i < nums.size(); i++) {
            tmp_vec.push_back(nums[i]);
            vector<int> new_nums = nums;
            new_nums.erase(new_nums.begin() + i);
            permute_helper(new_nums, results, tmp_vec);
            tmp_vec.pop_back();
        }
    }
};

Another solution:
Data structure:
steps:
Complexity:
Runtime:
Space:
Code:

Things to learn:
Advertisements

2 thoughts on “046. Permutations

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s