class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
if (nums.empty() || nums.size() == 0) return res;
vector<int> list;
helper(list, nums);
return res;
}
void helper(vector<int>& list, vector<int>& nums) {
if (list.size() == nums.size()) {
res.push_back(list);
return;
}
for (int i = 0; i < nums.size(); i++) {
auto p = find(list.begin(), list.end(), nums[i]); // O(N)
if (p != list.end()) continue;
list.push_back(nums[i]);
helper(list, nums);
list.erase(list.end() - 1); // backtrack push & delete
}
}
private:
vector<vector<int>> res;
};
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
if (nums.empty() || nums.size() == 0) return res;
helper(0, nums);
return res;
}
void helper(int count, vector<int>& nums) {
if (count == nums.size()) {
vector<int> list(nums.size());
for (int i = 0; i < nums.size(); i++) {
list[i] = nums[i];
}
res.push_back(list);
return;
}
for (int i = count; i < nums.size(); i++) {
swap(nums[count], nums[i]);
helper(count + 1, nums);
swap(nums[count], nums[i]);
}
}
private:
vector<vector<int>> res;
};
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
if (nums.empty() || nums.size() == 0) return res;
vector<int> cur;
helper(nums, cur);
return res;
}
void helper(vector<int>& nums, vector<int>& cur) {
if (cur.size() == nums.size()) res.push_back(cur);
for (int i = 0; i < nums.size(); i++) {
auto it = find(cur.begin(), cur.end(), nums[i]);
if (it != cur.end()) continue;
cur.push_back(nums[i]);
helper(nums, cur);
cur.pop_back();
}
}
private:
vector<vector<int>> res;
};
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
if (nums.size() == 0) return res;
vector<int> comb;
helper(nums, comb);
return res;
}
void helper(vector<int>& nums, vector<int>& comb) {
if (nums.size() == comb.size()) {
res.push_back(comb);
return;
}
for (int i = 0; i < nums.size(); i++) {
auto it = find(comb.begin(), comb.end(), nums[i]);
if (it != comb.end()) continue;
comb.push_back(nums[i]);
helper(nums, comb);
comb.pop_back();
}
}
private:
vector<vector<int>> res;
};
用什么:Backtracking
为什么:Backtracking典型题,找到所有组合
思路:
时间:
这种形式的递归大多都是O(n!)
空间:O(n)
47