C++ 0046.cpp
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
do
{
result.push_back(nums);
} while (next_permutation(nums.begin(), nums.end()));
return result;
}
}
Difficulty
and has an acceptance rate of about 82% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation generates all possible permutations of a given integer array. It leverages the C++ Standard Library to sort the input and then iteratively produce each lexicographically ordered arrangement using next_permutation. The result is collected in a two-dimensional vector that is returned to the caller.
Key Steps
The algorithm can be broken down into three distinct operations, each reflected in the source code.
Sorting the Input
Before permutation generation begins, the input vector is sorted to establish the smallest lexicographic order. This guarantees that next_permutation will enumerate every arrangement exactly once.
sort(nums.begin(), nums.end());
Iterative Generation with next_permutation
A do … while loop is employed so that the initial (sorted) configuration is captured before any transformation. Inside the loop, the current ordering of nums is appended to the result container. The loop continues as long as next_permutation can produce a new ordering.
do
{
result.push_back(nums);
} while (next_permutation(nums.begin(), nums.end()));
Returning the Accumulated Permutations
After the loop terminates, the fully populated result vector, containing every permutation, is returned to the caller.
return result;
Edge Cases Handled
The logic naturally accommodates several boundary conditions without additional checks.
When the input vector is empty, the sort call is a no-op, and the do … while loop executes exactly once. Consequently, the function returns a vector containing a single empty permutation, which aligns with the mathematical definition of the permutation of an empty set.
For a single-element vector, sorting leaves the element unchanged, the loop records that sole arrangement, and next_permutation immediately reports that no further ordering exists. The result therefore consists of one permutation containing the original element.
If the input contains duplicate values, sorting groups identical elements together. next_permutation then traverses the space of distinct lexicographic sequences, effectively producing each unique permutation without repetition. This behavior ensures that the output does not contain duplicate rows even when the source data has repeated numbers.
Performance Optimizations
The implementation benefits from several implicit optimizations provided by the Standard Library.
Sorting the array once at the start establishes a deterministic starting point, allowing next_permutation to run in linear time per iteration without needing to recompute ordering from scratch.
Using next_permutation avoids recursive backtracking, which would otherwise require additional call-stack overhead and potentially repeated allocation of temporary containers. The iterative approach keeps the algorithm’s memory footprint low and makes use of in-place swaps, reducing the amount of data movement.
Appending each permutation with push_back stores the vectors contiguously in the result container, taking advantage of std::vector’s amortized allocation strategy. This results in efficient memory usage as the container grows to accommodate the full set of permutations.
Overall, the combination of a single sort, an in-place permutation generator, and contiguous storage yields a solution that is both concise and performant for the task of enumerating all permutations.
ELI5 - Simplified Explanation
Imagine you have a handful of colorful building blocks laid out in a row. Sometimes you want to see every possible way to arrange those blocks in different orders. This computer code acts like a magical helper that finds all those different patterns for you.
First, the code lines up the blocks from the smallest to the largest one, just like tidying up before starting a game. Once they are in a nice, neat line, the computer takes a snapshot of that arrangement and puts it into a collection bag. Then, it uses a special trick to shuffle the blocks into the very next possible order. It keeps taking a new snapshot and shuffling the blocks over and over again. The computer is so clever that it knows exactly when it has tried every single possible combination, and once it has reached the very last one, it stops its work. Every time a new order is made, it gets tucked safely into the bag so you can see all the different ways the blocks can stand in a line.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | Python | C++ | Java | TS | |||||||
| WalkCCC | Python | C++ | Java | |||||||||
| leetcode.ca | Python | C++ | Java | C# | Rust | JS | Go | TS | ||||
| LeetcodeHelp | Python | C++ | Java | |||||||||
| MemoryLimitExceeded | Python | C++ | ||||||||||
| Progiez | Python | C++ | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | Python | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python, Python | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | Python | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 31: Next Permutation
- problem 47: Permutations II
- problem 60: Permutation Sequence
- problem 77: Combinations
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality