[LeetCode] Permutations

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

 

DFS

 1 class Solution {
 2 private:
 3     vector<vector<int> > ret;
 4     bool canUse[100];
 5     int a[100];
 6 public:
 7     void dfs(int dep, int maxDep, vector<int> &num)
 8     {
 9         if (dep == maxDep)
10         {
11             vector<int> ans;
12             for(int i = 0; i < maxDep; i++)
13                 ans.push_back(a[i]);
14             ret.push_back(ans);
15             return;
16         }
17         
18         for(int i = 0; i < maxDep; i++)
19             if (canUse[i])
20             {
21                 canUse[i] = false;
22                 a[dep] = num[i];
23                 dfs(dep + 1, maxDep, num);
24                 canUse[i] = true;
25             }       
26     }
27     
28     vector<vector<int> > permute(vector<int> &num) {
29         // Start typing your C/C++ solution below
30         // DO NOT write int main() function
31         ret.clear();
32         memset(canUse, true, sizeof(canUse));
33         dfs(0, num.size(), num);
34         return ret;
35     }
36 };
posted @ 2012-11-13 13:06  chkkch  阅读(638)  评论(0编辑  收藏  举报