您的位置:首页 > 其它

LeetCode (Permutations)

2017-05-03 12:47 381 查看
Problem:

Given a collection of distinct 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],
[3,2,1]
]

Solution:
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
if (nums.empty() || nums.size() == 1){
return {nums};
}
vector<int> num = nums;
num.erase(num.begin());
vector<vector<int>> b = permute(num);
for (int j = 0; j < b.size(); j++)
for (int l = 0; l < nums.size(); l++){
vector<int> p = b[j];
p.insert(p.begin() + l, nums[0]);
ans.push_back(p);
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: