来源:Leetcode
原帖:http://oj.leetcode.com/problems/permutations/
题目:
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].
代码:
原帖:http://oj.leetcode.com/problems/permutations/
题目:
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].
代码:
class Solution {
public:
vector<vector<int>> permute(vector<int> &num) {
if (num.empty()) {}
vector<vector<int> > result;
vector<bool> avail(num.size(), true);
vector<int> onepum;
permuteHelper(num, avail, onepum, result);
return result;
}
void permuteHelper(const vector<int> &num, vector<bool> &avail, vector<int> &onepum, vector<vector<int>> &result) {
if (onepum.size() == num.size()) {
result.push_back(onepum);
return;
}
for (int i = 0; i < num.size(); ++i) {
if (avail[i]) {
avail[i] = false;
onepum.push_back(num[i]);
permuteHelper(num, avail, onepum, result);
onepum.pop_back();
avail[i] = true;
}
}
}
};
No comments:
Post a Comment