http://www.lintcode.com/en/problem/permutations/#
Given a list of numbers, return all possible permutations.
Example
For nums =
[1,2,3], the permutations are:[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
vector<vector<int> > permute(vector<int> nums) {
// write your code here
vector<vector<int>> paths;
if (nums.empty()) {
return paths;
}
vector<int> index;
vector<int> path;
permuteHelper(nums, index, path, paths);
return paths;
}
private:
void permuteHelper(const vector<int> &nums,
vector<int> &index,
vector<int> &path,
vector<vector<int>> &paths) {
if (path.size() == nums.size()) {
paths.push_back(path);
return;
}
for (int ix = 0; ix < nums.size(); ix++) {
if (find(index.begin(), index.end(), ix) == index.end()) {
index.push_back(ix);
path.push_back(nums[ix]);
permuteHelper(nums, index, path, paths);
index.pop_back();
path.pop_back();
}
}
}
};原文:http://www.cnblogs.com/jianxinzhou/p/4523416.html