您的位置:首页 > 其它

LeetCode 46 - Permutations

2016-03-04 17:11 357 查看

Permutations

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]
,
and 
[3,2,1]
.

My Code

class Solution {
public:
void doPermute(vector<vector<int> >& res, vector<int> r, vector<int> v)
{
int size = v.size();
if (size == 1)
{
r.push_back(v[0]);
res.push_back(r);
return;
}

for (int i = 0; i < size; i++)
{
vector<int> rr(r);
vector<int> vv(v);
rr.push_back(v[i]);
vv.erase(vv.begin() + i);
doPermute(res, rr, vv);
}
}

vector<vector<int> > permute(vector<int>& nums) {
vector<vector<int> > res;
vector<int> r;
vector<int> v(nums);
doPermute(res, r, v);

return res;
}
};Runtime: 20 ms

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: