leetcode 46. 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], and [3,2,1].

集合中的元素沒有重複的。。。


解法一:

利用STL中的next_permutation函數來實現。

但是要注意,next_permutation是按字典順序取下一個排列,如果原始序列不是字典順序的話,則會有一部分排列無法取得。

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        //存放返回結果
       vector<vector<int>> res;
       //先將原始序列字典排序,確保後面使用next_permutation能夠得到全部的排序
       sort(nums.begin(),nums.end());

       res.push_back(nums);
       //注意next_permutation是按字典順序排序。如果原始的序列不是字典順序,則會有部分排列被省略
       while(next_permutation(nums.begin(),nums.end()))
       {
           res.push_back(nums);
       }
       return res;
    }
};

解法2:

利用劍指offer中的方式。

void nextPermute(vector<vector<int>> &res,vector<int>& nums,int begin)

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        //存放返回結果
       vector<vector<int>> res;
        if (nums.empty())
            return res;
        nextPermute(res, nums, 0);
       return res;
    }

    void nextPermute(vector<vector<int>> &res,vector<int>& nums,int begin){
        if(begin==nums.size()-1)
        {
           res.push_back(nums);
           return;
        }
        //遞歸三個主要的步驟~!swap,遞歸,在swap
        for(int i=begin;i!=nums.size();++i)
        {
            swap(nums[i],nums[begin]);
            nextPermute(res,nums,begin+1);
            swap(nums[i],nums[begin]);
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章