题目链接: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. 递归排列

这是一个排列的问题,首先联想到的就是递归方式。每次逐个固定每个元素到第一位置,然后递归排列剩下的元素。当固定到前面的元素数量等于数组长度的时候,递归终止。

时间复杂度:O(n!)(结果数量)

空间复杂度:O(n!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution
{
public:
    vector<vector<int> > permute(vector<int> &num)
    {
        vector<vector<int> > vvi;
        permute(num, 0, vvi);
        return vvi;
    }
private:
    void permute(vector<int> &num, int i, vector<vector<int> > &vvi)
    {
        if(i == num.size())
        {
            vvi.push_back(num);
            return;
        }
        for(int j = i; j < num.size(); ++ j)
        {
            swap(num[i], num[j]);
            permute(num, i + 1, vvi);
            swap(num[i], num[j]);
        }
    }
};
  1. next_permutation

其实还可以利用next_permutation()函数,逐步生成下一个排列。由于next_permutation()在最后一个排列时返回false,因此可以先对数组排序,然后调用next_permutation()直到其返回false。

时间复杂度:O(n!)(结果数量)

空间复杂度:O(n!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution
{
public:
    vector<vector<int> > permute(vector<int> &num)
    {
        sort(num.begin(), num.end());
        
        vector<vector<int> > vvi({num});
        while(next_permutation(num.begin(), num.end()))
            vvi.push_back(num);
        
        return vvi;
    }
};