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

     1 class Solution {
     2 public:
     3     vector<vector<int> > permute(vector<int> &num) {
     4         vector<vector<int> > result;
     5         sort(num.begin(), num.end());
     6         vector<int> path;
     7         dfs(num, path, result);
     8         return result;
     9     }
    10 private:
    11     void dfs(vector<int> &num, vector<int> &path, vector<vector<int>> &result) {
    12         if (path.size() == num.size()) {
    13             result.push_back(path);
    14             return;
    15         }
    16         for (auto i : num) {
    17             if (find(path.begin(), path.end(), i) == path.end()) {
    18                 path.push_back(i);
    19                 dfs(num, path, result);
    20                 path.pop_back();
    21             }
    22         } 
    23     }
    24 };
    View Code

    可以利用next permutation的方法,一个一个求,也可以用dfs的方法来求所有的排列。上面的代码是dfs版。

  • 相关阅读:
    Spring(3)
    Spring(2)
    Spring(1)
    2016年给自己的一个清单计划
    今天早上是我第一次发博客,请大家多多关照
    QTP知识积累
    [转]基于实际测试的功能测试点总结
    Django之模板
    Django之视图
    HTML
  • 原文地址:https://www.cnblogs.com/dengeven/p/3608081.html
Copyright © 2020-2023  润新知