[Leetcode 53] 46 Permutations

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:

 1 class Solution {
 2 public:
 3     vector<vector<int> > res;
 4 
 5     vector<vector<int> > permute(vector<int> &num) {
 6         // Start typing your C/C++ solution below
 7         // DO NOT write int main() function
 8         if (num.size() == 0) return res;
 9         
10         res.clear();
11         vector<int> r;
12         vector<int> tag(num.size(), 0);
13         bc(r, tag, num);
14         
15         return res;
16     }
17     
18     void bc(vector<int> path, vector<int> &tag, vector<int> &num) {
19         if (path.size() == num.size()) {
20             res.push_back(path);
21             return ;
22         }
23         
24         for (int i=0; i<num.size(); i++) {
25             if (tag[i] == 0) {
26                 path.push_back(num[i]);
27                 tag[i] = 1;
28                 bc(path, tag, num);
29                 tag[i] = 0;
30                 path.pop_back();
31             }   
32         }
33         
34         return ;
35     }
36 };
View Code

 

posted on 2013-05-26 05:58  freeneng  阅读(113)  评论(0编辑  收藏  举报

导航