leetcode: Permutations

http://oj.leetcode.com/problems/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].

思路

典型的递归问题。

  1. 生成[2, 3]的全排列[2, 3]和[3, 2],然后把1加上去生成[1, 2, 3]和[1, 3, 2]。
  2. 交换1和2的位置,生成[1, 3]的全排列[1, 3]和[3, 1],然后把2加上去生成[2, 1, 3]和[2, 3, 1]。
  3. 在第二步的基础上交换2和3的位置,生成[2, 1]的全排列[2, 1]和[1, 2],然后把3加上去生成[3, 2, 1]和[3, 1, 2]。
 1 class Solution {
 2 public:
 3     void internalPermute(vector<int> &num, int index, vector<int> &perm, vector<vector<int> > &result) {
 4         int size = num.size();
 5         
 6         if (size == index) {
 7             result.push_back(perm);
 8         }
 9         else {
10             for (int i = index; i < size; ++i) {
11                 swap(num[index], num[i]);
12                 perm.push_back(num[index]);
13                 internalPermute(num, index + 1, perm, result);
14                 perm.pop_back();
15                 swap(num[index], num[i]);
16             }
17         }
18     }
19     
20     vector<vector<int> > permute(vector<int> &num) {
21         vector<vector<int> > result;
22         vector<int> perm;
23         
24         internalPermute(num, 0, perm, result);
25         
26         return result;
27     }
28 };

 

posted @ 2013-11-12 14:28  移山测试工作室黑灯老师  阅读(2556)  评论(0编辑  收藏  举报
count website visits
Buy Computers