您的位置:首页 > 其它

[Leetcode 53] 46 Permutations

2013-05-26 05:58 429 查看
Problem:

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]
.

Analysis:

It's a backtracking problem. In order to make sure that we don't access the same element multiple times, we use an extra tag array to keep the access information. Only those with tag value equals 0 will be chose as candidates.

Code:

class Solution {
public:
vector<vector<int> > res;

vector<vector<int> > permute(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (num.size() == 0) return res;

res.clear();
vector<int> r;
vector<int> tag(num.size(), 0);
bc(r, tag, num);

return res;
}

void bc(vector<int> path, vector<int> &tag, vector<int> &num) {
if (path.size() == num.size()) {
res.push_back(path);
return ;
}

for (int i=0; i<num.size(); i++) {
if (tag[i] == 0) {
path.push_back(num[i]);
tag[i] = 1;
bc(path, tag, num);
tag[i] = 0;
path.pop_back();
}
}

return ;
}
};


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