LeetCode #46 Permutations

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SquirrelYuyu/article/details/82563632

(Week 1 算法作业)

题目:

https://leetcode.com/problems/permutations/description/

Given a collection of distinct integers, return all possible permutations.

Difficulty: Medium

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

即是求给出的一组不同整数的所有不同排列。


分析:

以[1 2 3]为例,我们手算时一般会这么做:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

但是本人认为按这个有序的步骤来编写程序,需要额外的标记来指明每次需要取哪个数字放到某一位上,比较麻烦。

经过观察,有如下规律:(第几位指从左到右的第几个数字)

排列的生成规律

总的来说,就是要不断进行不同的数位交换。每次交换后产生的新排列们也参与之后的交换。

所以,有以下算法:

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> result;
        result.push_back(nums);
        int size = nums.size();
        for(int i = size - 2; i >= 0; i--){
            int ss = result.size();
            for(int k = 0; k < ss; k++){    // 先前的结果集合中的每个排列都要参与接下来的交换
                for(int j = size - 1; j > i; j--){
                    vector<int> nn = result[k];
                    int tmp = nn[j];    // 交换第i位和第j位
                    nn[j] = nn[i];
                    nn[i] = tmp;
                    result.push_back(nn);
                }
            }

        }
        return result;
    }
};

时间复杂度为 O ( n ! ) ,其中n为给出的数字个数。
用时为8ms。

猜你喜欢

转载自blog.csdn.net/SquirrelYuyu/article/details/82563632