zoukankan      html  css  js  c++  java
  • [刷题] 46 Permutations

    要求

    • 整型数组,每个元素不相同,返回元素所有排列的可能

    示例

    • [1,2,3]
    • [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]

    思路

    • 树形问题,回溯法

    实现

    • permute():生成所有排列
    • generatePermutation():生成一个排列
    • nums:向量,输入
    • res:二维向量,保存生成的排列
    • p:向量,找到的一个排列
    • used:向量,记录nums中的第i个元素是否被使用过
    • 32-33:回溯,将p和used恢复原状,进行下一轮循环
     1 #include <vector>
     2 #include <iostream>
     3 #include <string>
     4 
     5 using namespace std; 
     6 
     7 class Solution {
     8     
     9 private:
    10     vector<vector<int>> res;
    11     vector<bool> used;
    12     
    13     // 生成nums中元素的排列,index--正在处理第几个元素,p--找到的一个排列 
    14     // p中保存一个有index个元素的排列
    15     // 向p末尾添加第index+1个元素,获得一个有index+1个元素的排列 
    16     void generatePermutation( const vector<int>& nums, int index, vector<int>& p ){
    17         
    18         if( index == nums.size() ){
    19             cout<<"p = "<< p[0] << p[1] << p[2] << endl;
    20             res.push_back(p);
    21             return;
    22         }
    23         
    24         for( int i = 0 ; i < nums.size(); i ++ )
    25             if( !used[i] ){
    26                 // 将nums[i]添加在p中
    27                 p.push_back( nums[i] );
    28                 used[i] = true;
    29                 cout<<"nums["<<i<<"] = "<<nums[i]<<endl;
    30                 generatePermutation(nums, index+1, p); 
    31                 // 状态回溯 
    32                 p.pop_back();
    33                 used[i] = false;
    34             }
    35         return;
    36     }
    37 
    38 public:
    39     vector<vector<int>> permute(vector<int>& nums) {
    40         
    41         res.clear();
    42         if( nums.size() == 0 )
    43             return res;
    44         
    45         used = vector<bool>(nums.size(), false);
    46         vector<int> p;
    47         generatePermutation( nums, 0, p);
    48         
    49         return res;
    50     }
    51 };
    52 
    53 int main(){
    54     vector<int> v{1,2,3};
    55     vector<vector<int>> res = Solution().permute(v);
    56     
    57     return 0;
    58 }
    View Code

        

    相关

    • 47 Permutation II
  • 相关阅读:
    POJ 3140 Contestants Division (树dp)
    POJ 3107 Godfather (树重心)
    POJ 1655 Balancing Act (树的重心)
    HDU 3534 Tree (经典树形dp)
    HDU 1561 The more, The Better (树形dp)
    HDU 1011 Starship Troopers (树dp)
    Light oj 1085
    Light oj 1013
    Light oj 1134
    FZU 2224 An exciting GCD problem(GCD种类预处理+树状数组维护)同hdu5869
  • 原文地址:https://www.cnblogs.com/cxc1357/p/12702849.html
Copyright © 2011-2022 走看看