题目描述:

Given a collection of distinct 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],
  [3,2,1]
]

题目要我们找到数组(无重复元素)的所有排列组合。

解题思路:

这道题的思路还是很好想的:

首先当n(元素个数)=2时有两种排列方式;

然后当n>2时,an=n*a(n-1)。

代码:

 1 class Solution {
 2 public:
 3     void selectAll(vector<vector<int>>& ret, vector<int> cur, int index, int& n){
 4         if(index == n-1)
 5             ret.push_back(cur);
 6         else{
 7             for(int i = index; i < n; i++){
 8                 if(i != index)
 9                     swap(cur[index],cur[i]);
10                 selectAll(ret, cur, index+1, n);
11             }
12         }
13     }
14     vector<vector<int>> permute(vector<int>& nums) {
15         int n = nums.size();
16         vector<vector<int>> ret;
17         if(n < 2){
18             ret.push_back(nums);
19             return ret;
20         }
21         selectAll(ret, nums, 0, n);
22         return ret;
23     }
24 };

 

 

 

posted on 2018-03-01 22:51  宵夜在哪  阅读(88)  评论(0)    收藏  举报