题目链接
问题描述
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
解题思路
这是求一个数组的全排列。使用DFS的方法,用path向量记录每一种排列,并将path存储到ret中。每次将nums中元素push到path前都要检查该元素是否已经在path中存在,可以通过将nums元素的index存入pickIndex向量进行记录来解决这个问题。代码如下:
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > ret;
vector<int> order;
vector<int> pickIndex;
if (nums.size() == 0) return ret;
helper(nums, 0, pickIndex, order, ret);
return ret;
}
void helper(vector<int>& nums, int nowIndex, vector<int>& pickIndex, vector<int>& order, vector<vector<int> >& ret) {
if (pickIndex.size() == nums.size()) {
ret.push_back(order);
return;
}
vector<int>::iterator it;
for (int i = 0; i < nums.size(); i++) {
it = find(pickIndex.begin(), pickIndex.end(), i);
if (it != pickIndex.end()) continue;
pickIndex.push_back(i);
order.push_back(nums[i]);
helper(nums, nowIndex, pickIndex, order, ret);
pickIndex.pop_back();
order.pop_back();
}
}
};