您的位置:首页 > 其它

LeetCode: Permutations

2012-12-05 14:50 309 查看
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]
.

固定第一位,然后算后面的全排列。然后再将第一位固定为其他的值。

Crack Code Interview上给的方法是先固定一个值,找出剩下的值的全排列,然后在把这个固定的值插入到不同的位置,得到新的全排列。
感觉写起来不如这个直观。

class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res;
vector<int> rcd;
subPermute(res, num, rcd);
return res;
}
void subPermute(vector<vector<int> > &res, vector<int> &num, vector<int> &rcd){
if(num.size() == 0){
res.push_back(rcd);
return;
}
for(int i = 0; i < num.size(); ++i){
vector<int> temp = num;
rcd.push_back(temp[i]);
for(int j = i; j < num.size() -1 ;++j){
temp[j] = temp[j+1];
}
temp.pop_back();
subPermute(res, temp, rcd);
rcd.pop_back();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: