码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】046. Permutations

时间:2017-04-26 10:04:05      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:example   元素   csharp   color   arp   following   return   next   oss   

题目:

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

  

题解:

  之前解过Next Permutation,故这个题可以重复调用nextPermutation函数产生全排列

Solution 1 ()

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        for(int i=n-2; i>=0; --i) {
            if(nums[i]>=nums[i+1]) continue;
            int j = n-1;
            for(; j>i; --j) {
                if(nums[j]>nums[i]) break;
            }
            swap(nums[i], nums[j]);
            reverse(nums.begin()+i+1, nums.end());
            return;            
        }
        reverse(nums.begin(), nums.end());
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> vv;
        vector<int> v = nums;
        vv.push_back(v);
        nextPermutation(v);
        while(v != nums) {
            vv.push_back(v);
            nextPermutation(v);
        }
        return vv;
    }
};

  其实这个问题很容易想到递归的解法,取第一个数后对剩下的元素进行全排列

Solution 2 ()

 

【LeetCode】046. Permutations

标签:example   元素   csharp   color   arp   following   return   next   oss   

原文地址:http://www.cnblogs.com/Atanisi/p/6766880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!