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

    Analyse: 

        (1) Swap the 1st element with all the elements, including itself.
           (2) Then the 1st element is fixed, go to the next element.
           (3) Until the last element is fixed. Output.

    new version:

     1 class Solution {
     2 public:
     3     //swap the first number with every number in the nums vector
     4     //then fixed the new first number, and do the same process for the remaining numbers
     5     //after reaching (nums.size() - 1)'s depth, push the vector into result
     6     //then swap the two number back (backtracking to the original state)
     7     vector<vector<int>> permute(vector<int>& nums) {
     8         vector<vector<int> > result;
     9         if(nums.empty()) return result;
    10         
    11         helper(result, nums, 0);
    12         return result;
    13     }
    14     
    15     void helper(vector<vector<int> >& result, vector<int>& nums, int depth){
    16         if(depth == nums.size() - 1){
    17             result.push_back(nums);
    18             return;
    19         }
    20         
    21         for(int i = depth; i < nums.size(); i++){
    22             swap(nums[i], nums[depth]);
    23             helper(result, nums, depth + 1);
    24             swap(nums[i], nums[depth]);
    25         }
    26     }
    27 };

    Runtime: 16ms

     1 class Solution {
     2 public:
     3     vector<vector<int>> permute(vector<int>& nums) {
     4         vector<vector<int> > result;
     5         if(nums.empty()) return result;
     6         
     7         helper(result, nums, 0, nums.size() - 1);
     8         return result;
     9     }
    10     
    11     void helper(vector<vector<int> >& result, vector<int> nums, int depth, int n){
    12         if(depth == n){
    13             result.push_back(nums);
    14             return;
    15         }
    16         for(int i = depth; i < nums.size(); i++){
    17             swap(nums[depth], nums[i]);
    18             helper(result, nums, depth + 1, n);
    19             swap(nums[depth], nums[i]);
    20         }
    21     }
    22 };
  • 相关阅读:
    Linux常用命令
    C# 报表设计器 (winform 设计端)开发与实现生成网页的HTML报表
    完成复杂表头列表
    流程设计--页面介绍
    流程设计--设计理念
    报表设计--坐标实例-位移坐标
    Spring MVC 工作原理--自我理解
    java ==、equals和hashCode的区别和联系
    java 自动装箱和拆箱
    java maven笔记
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4873385.html
Copyright © 2011-2022 走看看