Permutations 题解
题目来源:https://leetcode.com/problems/permutations/description/
Description
Given a collection of distinct numbers, return all possible permutations.
Example
For example,
[1,2,3]
have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Solution
class Solution {
private:
void backTrack(vector<vector<int> >& res, vector<int>& nums, int index) {
if (index >= nums.size()) {
res.push_back(nums);
} else {
int i, size = nums.size();
for (i = index; i < size; i++) {
swap(nums[i], nums[index]);
backTrack(res, nums, index + 1);
swap(nums[i], nums[index]);
}
}
}
public:
vector<vector<int> > permute(vector<int>& nums) {
vector<vector<int> > res;
if (nums.empty())
return res;
backTrack(res, nums, 0);
return res;
}
};
解题描述
这道题题意是求给定数组(元素互不相同)的全排列。用到的算法是递归回溯,元素交换起始位index
初值为0,每次进入回溯函数交换index
及其后某个位置上的元素,再将index + 1
使用递归回溯,以穷尽所有可能的排列情况并且不会重复相同情形。