46. Permutations (Back-Track,Sort)

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].

思路:遍历数组,对于该字母,它可选择与它之后的字母交换或者是不交换=>带回溯的递归

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        result.clear();  
        dfs(num,0);
        return result;
        
    }
    void dfs(vector<int> num, int depth)
    {
        if(depth == num.size()-1)
        {
            result.push_back(num);
            return;
        }
        dfs(num,depth+1);
        int temp = num[depth];
        for(int i = depth+1;i< num.size(); i++)
        {
            num[depth] = num[i];
            num[i] = temp;
            dfs(num,depth+1);
            num[i] = num[depth];
            num[depth] = temp;
        }
    }
    
private:
    vector<vector<int> >  result;
};

 思路II:

当字符串长度为2时 a1a2 a2a1
当字符串长度为3时 a3a1a2 a1a3a2 a1a2a3 a3a2a1 a2a3a1 a2a1a3
比较可以得到 其实就是把a3(多出来的元素)插在长度为2时的两个字符串的任意位置

时间复杂度:三个for循环 O(n3)

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        int size = nums.size();
        int resultSize;
        int resultIndex; 
        vector<vector<int>> result; 
        vector<int> resultItem(1,nums[0]);
        result.push_back(resultItem);
        for(int i = 1; i <size; i++){ //nums[i] is the num to insert
            resultSize = result.size(); //resultSize in the preceeding insert iterate
            for(int j = 0; j < resultSize; j++){ //iterate the array to do insertion
                result[j].push_back(nums[i]);
                resultIndex = j;
                for(int k = i-1; k >=0; k--){ //like insertion sort, adjust forward
                    result.push_back(result[resultIndex]);
                    result[result.size()-1][k+1] = result[resultIndex][k];
                    result[result.size()-1][k] = result[resultIndex][k+1];
                    resultIndex = result.size()-1;
                }
            }
        }
        return result;
    }
};

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/4855304.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值