您的位置:首页 > 其它

Permutations

2015-10-13 02:20 253 查看
Given a collection of numbers, return all possible permutations.

For example,
[1,2,3]
have the following permutations:
[1,2,3]
,
[1,3,2]
,
[2,1,3]
,
[2,3,1]
,
[3,1,2]
, and
[3,2,1]
.

Analyse:

   (1) Swap the 1st element with all the elements, including itself.
(2) Then the 1st element is fixed, go to the next element.
(3) Until the last element is fixed. Output.

new version:

class Solution {
public:
//swap the first number with every number in the nums vector
//then fixed the new first number, and do the same process for the remaining numbers
//after reaching (nums.size() - 1)'s depth, push the vector into result
//then swap the two number back (backtracking to the original state)
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > result;
if(nums.empty()) return result;

helper(result, nums, 0);
return result;
}

void helper(vector<vector<int> >& result, vector<int>& nums, int depth){
if(depth == nums.size() - 1){
result.push_back(nums);
return;
}

for(int i = depth; i < nums.size(); i++){
swap(nums[i], nums[depth]);
helper(result, nums, depth + 1);
swap(nums[i], nums[depth]);
}
}
};


Runtime: 16ms

class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > result;
if(nums.empty()) return result;

helper(result, nums, 0, nums.size() - 1);
return result;
}

void helper(vector<vector<int> >& result, vector<int> nums, int depth, int n){
if(depth == n){
result.push_back(nums);
return;
}
for(int i = depth; i < nums.size(); i++){
swap(nums[depth], nums[i]);
helper(result, nums, depth + 1, n);
swap(nums[depth], nums[i]);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: