Leetcode每日一题:46.permutations(全排列)_递归
思路:
Leetcode每日一题:46.permutations(全排列)_递归_02
也可以用递归来求解 但是对应开销要大 且递归的核心部分也没有变化

//非递归法
#include <iostream>
#include <vector>
using namespace std;
/*
Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
*/

vector<vector<int>> permute(vector<int> &nums)
{
    vector<vector<int>> res;
    if(nums.size()==0) return res;
    int len=nums.size();
    vector<int> temp;
    temp.push_back(nums[0]);
    res.push_back(temp);

    for(int i=1;i<len;i++)
    {
        vector<vector<int>> resNew;
        for(auto s : res)
        {
            //加在前面
            s.insert(s.begin(),nums[i]);
            resNew.push_back(s);
            s.erase(s.begin());
            //加在后面
            s.push_back(nums[i]);
            resNew.push_back(s);
            s.pop_back();
            //加在中间
            int lenS=s.size();
            for(int j=1;j<=lenS-1;j++)
            {
                s.insert(s.begin()+j,nums[i]);
                resNew.push_back(s);
                s.erase(s.begin()+j);
            }
        }
        res=resNew;
    }

    return res;
}

int main()
{
    vector<int> test;
    test.push_back(1);
    test.push_back(2);
    test.push_back(3);
    vector<vector<int>> res=permute(test);
    for(auto a :res)
    {
        for(auto b:a)
        {
            cout<<b<<' ' ;
        }
        cout<<endl;
    }
    return 0;
}