zoukankan      html  css  js  c++  java
  • Leetcode:46. Permutations

    Description

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

    Example

    For example,
    [1,2,3] have the following permutations:
    
    [
        [1,2,3],
        [1,3,2],
        [2,1,3],
        [2,3,1],
        [3,1,2],
        [3,2,1]
    ]
    

    思路

    • 自己写了一个getNextPermute函数
    • STL里面有一个next_permutation函数

    代码

    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            vector<vector<int>> res;
            int len = nums.size();
            if(len == 0) return res;
            if(len == 1) {
                res.push_back(nums);
                return res;
            }
            
            sort(nums.begin(), nums.end());
            
            do{
                res.push_back(nums);
            }
            while(getNextPermute(nums, len));
            
            return res;    
        }
        
        bool getNextPermute(vector<int>& nums, int len){
            int index1 = 0, index2 = -1, flag = nums[0];
            for(int i = 1; i < len; ++i){
                if(nums[i] > nums[i - 1]){
                    index1 = i - 1;
                    index2 = i;
                    flag = nums[i] - nums[i - 1];
                }
                else if(nums[i] > nums[index1] && nums[i] - nums[index1] < flag){
                    index2 = i;
                    flag = nums[i] - nums[index1];
                }
            }
            
            if(index2 == -1) return false;
            
            swap(nums[index1], nums[index2]);
            sort(nums.begin() + index1 + 1, nums.end());
            return true;
        }
    };
    
    • next_permutation
    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            vector<vector<int>> res;
            int len = nums.size();
            if(len == 0) return res;
            if(len == 1) {
                res.push_back(nums);
                return res;
            }
            
            sort(nums.begin(), nums.end());
            
            do{
                res.push_back(nums);
            }
            while(next_permutation(nums.begin(), nums.end()));
            
            return res;    
        }
    };
    
  • 相关阅读:
    C++指针和引用及区别
    C/C++中extern关键字总结
    php进阶面试题总结
    算法疑难(js实现)---11、字典树
    Trie|如何用字典树实现搜索引擎的关键词提示功能
    ExtJS表格——行号、复选框、选择模型
    Ext.js 中 25种类型的Ext.panel.Tool
    Ext NumberField使用
    [ext]form.submit()相关说明
    ExtJS 表单 submit时错误处理
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6847492.html
Copyright © 2011-2022 走看看