zoukankan      html  css  js  c++  java
  • Permutations

    Permutations

    Given a collection of distinct 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],
      [3,2,1]
    ]

    分析: 全排列实现思想是从start开始,分别和后面的数进行交换,递归求解

    class Solution {
    public:
        void swap(int i, int j, vector<int>& nums){
            int temp =nums[i];
            nums[i] = nums[j];
            nums[j]= temp;
        }
        void allRange(int start, vector<int>& nums, vector<vector<int>>& res)
        {
            if(start==nums.size()-1)
                return;
            for(int i =start; i<nums.size(); i++){
                cout << start << " "<<i<<endl;
                swap(start, i, nums);
                if(start!=i)
                    res.push_back(nums);
                allRange(start+1, nums, res);
                swap(i, start, nums);
            }
        }
        vector<vector<int>> permute(vector<int>& nums) {
            vector<vector<int>> res;
            if(nums.size()==0)
                return res;
            res.push_back(nums);
            allRange(0, nums, res);
            return res;
            
        }
    };
    

      

  • 相关阅读:
    SQL注入的一般步骤及防范方法
    防止SQL注入的五种方法
    document.getElementById("orderform").submit() 提交给了谁?
    页面调试-F12
    rs.last()续
    rs.last()
    14课后习题
    HashMap
    链表
    习题
  • 原文地址:https://www.cnblogs.com/willwu/p/6227608.html
Copyright © 2011-2022 走看看