//
// Created by YUQIONG LI on 19/9/2018.
//
#include <vector>
#include <iostream>
using std::vector;
using std::cout;
using std::endl;
class Solution {
public:
void permuteHelper(vector<int> & nums, vector<int> chosen, vector<vector<int>> & res){
// no more choices to make
if (nums.empty()){
if (std::find(res.begin(), res.end(), chosen) == res.end())
res.push_back(chosen);
return;
}
// choose
for (int i = 0; i < nums.size(); i++){
int curr = nums[i];
chosen.push_back(curr);
nums.erase(nums.begin()+i);
// explore
permuteHelper(nums, chosen, res);
// un-choose
chosen.pop_back();
nums.insert(nums.begin()+i, curr);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<int> chosen;
vector<vector<int> > res;
permuteHelper(nums, chosen, res);
return res;
}
};
int main(){
vector<int> nums = {1, 2};
Solution s;
vector<vector<int>> res = s.permute(nums);
for (auto v : res){
std::cout << "Now print one sets of results.\n";
for (int e : v){
std::cout << e << ' ';
}
std::cout << endl;
}
return 0;
}
Mistakes:
- in finding and pushing to res, note using == end(), not != end()
- the base case condition is nums.size() == 0
Here might be some memory leak. Maybe could have done better.
- in finding and pushing to res, note using == end(), not != end()
- the base case condition is nums.size() == 0
Here might be some memory leak. Maybe could have done better.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.