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]
.
Classical backtrack.
In order to make the output in sequence, sort the inputs first.
void permute(vector<int>& nums, int depth, vector<vector<int>>& res, vector<int>& path, vector<int>& used) {
if(depth == nums.size()) res.push_back(path); // depth variable can be saved, if here checks path.size() == nums.size()
for(int i = 0; i < nums.size(); ++i) {
if(used[i] == false) {
used[i] = true; // use a flag to mark that the value has been used.
path.push_back(nums[i]);
permute(nums, depth + 1, res, path, used);
used[i] = false;
path.pop_back();
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
if(nums.size() == 0) return {};
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> path;
vector<int> used(nums.size(), false);
permute(nums, 0, res, path, used);
return res;
}