您的位置:首页 > 其它

【Leetcode】Permutations

2014-03-18 16:35 204 查看
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) {
vector<vector<int> > result;
sort(num.begin(), num.end());
vector<int> path;
dfs(num, path, result);
return result;
}
private:
void dfs(vector<int> &num, vector<int> &path, vector<vector<int>> &result) {
if (path.size() == num.size()) {
result.push_back(path);
return;
}
for (auto i : num) {
if (find(path.begin(), path.end(), i) == path.end()) {
path.push_back(i);
dfs(num, path, result);
path.pop_back();
}
}
}
};


View Code
可以利用next permutation的方法,一个一个求,也可以用dfs的方法来求所有的排列。上面的代码是dfs版。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: