zoukankan      html  css  js  c++  java
  • 46. Permutations 回溯算法

    https://leetcode.com/problems/permutations/

    求数列的所有排列组合。思路很清晰,将后面每一个元素依次同第一个元素交换,然后递归求接下来的(n-1)个元素的全排列。

    经过昨天的两道回溯题,现在对于回溯算法已经很上手了。直接貼代码:

    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            if(nums.size()==0)
                return res;
            int len=nums.size();
            vector<int> temp;
            helper(nums,0,0,len,temp);
            return res;
        }
    private:
        void helper(vector<int>& nums,int pos,int count,int len,vector<int>& temp);//pos用来控制位置,count用来控制个数,当count递增到len时,就说明已经到了一个全排列,递归回去时记得将count减1,并且temp要出栈之前压入的元素。
    private:
        vector<vector<int>> res;
    };
    
    void Solution::helper(vector<int>& nums,int pos,int count,int len,vector<int>& temp){
        if(count==len){
            res.push_back(temp);
            return;
        }
        for(int i=pos;i<len;i++){
            swap(nums[pos],nums[i]);
            temp.push_back(nums[pos]);//这儿可别写成了nums[i],害自己调试半天
            helper(nums,pos+1,++count,len,temp);
            temp.pop_back();
            count--;
            swap(nums[pos],nums[i]);
        }
    }
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    使用selenium模拟登陆12306以及滑块验证
    网络爬虫之requests模块
    网络爬虫简介
    MongoDB基础操作
    redis集群搭建以及常见问题
    redis的主从复制
    Linux下如何安装mysql
    python 序列化模块
    python os模块和sys模块
    python 时间模块
  • 原文地址:https://www.cnblogs.com/chess/p/5260666.html
Copyright © 2011-2022 走看看