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]);
        }
    }
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    [Panzura] identify user operations(copy, open, read ... ) in audit log
    Spark 学习
    Zeppelin 学习
    Delta Lake 学习
    传染病模型 SI
    xcodebuild和xcrun实现自动打包iOS应用程序
    控制UIlabel 垂直方向对齐方式的 方法
    ALAssetsLibrary
    CATransform3D
    AVFoundation的使用
  • 原文地址:https://www.cnblogs.com/chess/p/5260666.html
Copyright © 2011-2022 走看看