LeetCode题解–46. Permutations

来源:互联网 发布:螨虫与痘痘的知乎 编辑:程序博客网 时间:2024/06/05 16:53

链接

LeetCode题目:https://leetcode.com/problems/permutations

难度:Medium

题目

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

生成n个数字的所有排列情况。

分析

为了生成n个数字的所有排列情况,可以先生成后面n-1个数字的所有排列情况,然后第1个数字插到任意位置。而生成n-1个数字的排列也可以先从生成n-2个数字开始,以此类推,最后生成1个数字的排列情况只需要返回该数字。

代码

class Solution {public:    vector<vector<int>> permute(vector<int> &nums) {        vector<vector<int>> res;        for (int i = 0; i < nums.size(); i++) {            vector<vector<int>> temp = permute2(nums, 0, i);            for (auto x:temp) {                res.push_back(x);            }        }        return res;    }    vector<vector<int>> permute2(vector<int> &nums, int old_pos, int new_pos) {        vector<vector<int>> res;        if (nums.size() == 1) {            res.push_back(nums);        } else {            vector<int> temp;            for (int i = 0; i < old_pos; i++) {                temp.push_back(nums[i]);            }            for (int i = old_pos + 1; i < nums.size(); i++) {                temp.push_back(nums[i]);            }            auto all_permutes = permute(temp);            for (auto x:all_permutes) {                vector<int> temp2;                int i, j;                for (i = 0, j = 0; j < new_pos; i++, j++) {                    temp2.push_back(x[i]);                }                temp2.push_back(nums[old_pos]);                for (; j < x.size(); i++, j++) {                    temp2.push_back(x[i]);                }                res.push_back(temp2);            }        }        return res;    }};
0 0
原创粉丝点击