zoukankan      html  css  js  c++  java
  • [Leetcode] permutations 全排列

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

    题意:求给定数列的全排列。

    思路:使用DFS,这里有一点值得注意的是,在选取数字压入中间变量时,要确保,没有被访问过,这就要在遍历的同时,维护一个标识数组,标识对应元素的访问情况。代码如下:

     1 class Solution {
     2 public:
     3     vector<vector<int> > permute(vector<int> &num) 
     4     {
     5         vector<int> midVal;
     6         vector<vector<int>> res;
     7         vector<int> visited(num.size(),0);
     8         permuteDFS(num,0,midVal,res,visited);
     9         return res;         
    10     }
    11 
    12     void permuteDFS(vector<int> &num,int lev,vector<int> &midVal,
    13     vector<vector<int>> &res,vector<int> &visited)
    14     {
    15         if(lev==num.size())
    16             res.push_back(midVal);
    17         else
    18         {
    19             for(int i=0;i<num.size();++i)
    20             {
    21                 if(visited[i]==0)
    22                 {
    23                     visited[i]=1;
    24                     midVal.push_back(num[i]);
    25                     permuteDFS(num,lev+1,midVal,res,visited);
    26                     midVal.pop_back();
    27                     visited[i]=0;
    28                 }
    29                 
    30             }
    31         }    
    32     }
    33 };

    非递归版,可参加Code  Gander.

  • 相关阅读:
    svn Mac
    webpack实用配置
    vuex状态管理-数据改变不刷新
    element-vue-koa2-mysql实现文件上传
    Promise的理解
    mysql Mac篇
    python 24 days
    python 7 days
    python 27 days
    python 26 days
  • 原文地址:https://www.cnblogs.com/love-yh/p/7206248.html
Copyright © 2011-2022 走看看