zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    1074. Reversing Linked List (25)
    1056. Mice and Rice (25)
    1051. Pop Sequence (25)
    1001. A+B Format (20)
    1048. 数字加密(20)
    1073. Scientific Notation (20)
    1061. Dating (20)
    1009. 说反话 (20)
    MyBatis学习总结(8)——Mybatis3.x与Spring4.x整合
    MyBatis学习总结(8)——Mybatis3.x与Spring4.x整合
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4855304.html
Copyright © 2011-2022 走看看