Leetcode#46 Permutations

原题地址

 

方法I:排序+字典序枚举。生成字典序的方法见这里

方法II:排列树(其实就是DFS)

 

下图是一个排列树,每一层标红的字符是已经枚举完毕的部分,在后代节点中也不再变化;下划线的部分是待枚举排列的部分,在后代节点中将依次枚举。

Leetcode#46 Permutations_第1张图片

可见,排列树将问题一层一层分解为子问题,非常直观。如何从一个节点生成儿子节点呢?假设当前节点s[0..n],其中s[0..i]都已经枚举好了,s[i+1..n]是待枚举部分。那么,依次在s[i+1..n]中枚举s[i+1],现在s[0..i+1]变成已经排列好的了,要求s[i+2..n]的排列,如此递归下去。

 

代码:

 1 vector<vector<int> > res;
 2 
 3 void solve(vector<int> &num, int pos) {
 4   int n = num.size();
 5 
 6   if (pos == n)
 7     res.push_back(num);
 8   for (int i = pos; i < n; i++) {
 9     swap(num[pos], num[i]);
10     solve(num, pos + 1);
11     swap(num[pos], num[i]);
12   }
13 }
14 
15 vector<vector<int> > permute(vector<int> &num) {
16   solve(num, 0);
17   return res;
18 }

 

你可能感兴趣的:(LeetCode)