zoukankan      html  css  js  c++  java
  • 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].

    Hide Tags
     Backtracking
     
    建立一棵树,比如说
                                           1234
     
                   1234           2134           3214         4231     //就是swap(1,1)  swap(1,2) swap(1,3) swap(1,4)
                      |          
         1234  1324  1432                        //就是swap(2,2)  swap(2,3) swap(2,4) 
            |
      1234  1243                                  //就是swap(3,3)  swap(3,4) 
     
    然后,就用DFS遍历,叶子节点就是我们想要的
    class Solution {
    private:
        vector<vector<int> > ret;
    public:
        void perm(vector<int> num,int i){
            if(i==num.size()){
                ret.push_back(num);
                return;
            }
            for(int j=i;j<num.size();j++){
                swap(num[i],num[j]);            
                perm(num,i+1);                  
                swap(num[j],num[i]);           //复原,进行下一个交换前需复原之前状态
            }
        }
        vector<vector<int> > permute(vector<int> &num) {
            perm(num,0);
            return ret;
        }
    };
     
     
  • 相关阅读:
    CSS进阶(八) float
    CSS进阶(七)vertical-align
    CSS进阶(六) line-height
    CSS进阶(五)border
    CSS进阶(四)margin
    CSS进阶(三)padding
    ORA-01555 snapshot too old
    Ubuntu14.04LTS安装引发的蛋疼
    rancher 2 安装 longhorn
    rancher2 挂载ceph-rbd
  • 原文地址:https://www.cnblogs.com/li303491/p/4114500.html
Copyright © 2011-2022 走看看