Fork me on GitHub

[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],
[3,2,1]
]

思路:

参考别人的方法,将所有的数分别与第一个数交换。。。待学习。。

void permuteCore2(vector<vector<int>>& result, vector<int>& nums , int index)
    {
        if (index == nums.size())
        {
            result.push_back(nums);
        }
        for (int i = index; i < nums.size(); i++)
        {
            swap(nums[i], nums[index]);
            permuteCore2(result, nums,index + 1);
            swap(nums[i], nums[index]);
        }
    }
    void permuteCore(vector<vector<int>>& result,vector<int>& nums, vector<int>& temp,int index)
    {
        if (index == nums.size())
        {
            result.push_back(temp);
        }
        for (int i = index; i < nums.size();i++)
        {
            
            temp.push_back(nums[i]);
            swap(nums[i], nums[index]);
            permuteCore(result, nums, temp, index + 1);
            swap(nums[i], nums[index]);
            temp.pop_back();
            
        }
    }
    vector<vector<int>> permute(vector<int>& nums)
    {
        vector<vector<int>>result;
        vector<int> temp;
        sort(nums.begin(),nums.end());
        //permuteCore(result, nums, temp, 0);
        permuteCore2(result, nums,0);
        return result;
    }

 

参考:

http://blog.csdn.net/happyaaaaaaaaaaa/article/details/51534048

posted @ 2017-03-08 11:00  hellowOOOrld  阅读(172)  评论(0编辑  收藏  举报