zoukankan      html  css  js  c++  java
  • leetcode: Permutations

    http://oj.leetcode.com/problems/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. 生成[2, 3]的全排列[2, 3]和[3, 2],然后把1加上去生成[1, 2, 3]和[1, 3, 2]。
    2. 交换1和2的位置,生成[1, 3]的全排列[1, 3]和[3, 1],然后把2加上去生成[2, 1, 3]和[2, 3, 1]。
    3. 在第二步的基础上交换2和3的位置,生成[2, 1]的全排列[2, 1]和[1, 2],然后把3加上去生成[3, 2, 1]和[3, 1, 2]。
     1 class Solution {
     2 public:
     3     void internalPermute(vector<int> &num, int index, vector<int> &perm, vector<vector<int> > &result) {
     4         int size = num.size();
     5         
     6         if (size == index) {
     7             result.push_back(perm);
     8         }
     9         else {
    10             for (int i = index; i < size; ++i) {
    11                 swap(num[index], num[i]);
    12                 perm.push_back(num[index]);
    13                 internalPermute(num, index + 1, perm, result);
    14                 perm.pop_back();
    15                 swap(num[index], num[i]);
    16             }
    17         }
    18     }
    19     
    20     vector<vector<int> > permute(vector<int> &num) {
    21         vector<vector<int> > result;
    22         vector<int> perm;
    23         
    24         internalPermute(num, 0, perm, result);
    25         
    26         return result;
    27     }
    28 };
  • 相关阅读:
    Bootstrap按钮
    Bootstrap表单
    Bootstrap表格
    Bootstrap列表
    jq 的onchange事件
    php 跳出循环的几种方式
    php变量和字符串连接符——点
    php 从2维数组组合为四维数组分析
    mysql 删除表中记录
    mysql 聚合函数
  • 原文地址:https://www.cnblogs.com/panda_lin/p/permutations.html
Copyright © 2011-2022 走看看