https://leetcode.com/problems/permutations/description/
Solution 1.
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
perm(nums, 0, res);
return res;
}
void perm(vector<int>& nums, int idx, vector<vector<int>>& res) {
if(idx == nums.size()) {
res.push_back(nums);
return;
}
for(int i=idx; i<nums.size(); i++) {
// 0 ~ idx-1 are fixed, swap nums[idx] with nums[idx ~ nums.size()-1]
swap(nums[idx], nums[i]);
// after swap with nums[idx], fix nums[0 ~ idx], swap for idx+1 ~ end
perm(nums, idx+1, res);
// reset before work on i+1
swap(nums[idx], nums[i]);
}
}
Solution 2.
vector<vector<int>> permute(vector<int>& nums) {
if(nums.size() == 0) return {};
vector<vector<int>> res;
res.push_back(nums);
perm(nums, res, 1);
return res;
}
void perm(vector<int>&nums, vector<vector<int>>& res, int idx) {
if(idx == nums.size()) return;
int N = res.size();
for(int j=0; j<N; j++)
for(int i=0; i<idx; i++) {
vector<int> r = res[j];
swap(r[i], r[idx]);
res.push_back(r);
}
perm(nums, res, idx+1);
}
Solution 3.
vector<vector<int>> permute(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
do {
res.push_back(nums);
} while(next_permutation(nums.begin(), nums.end()));
return res;
}
No comments:
Post a Comment