首页 > 其他 > 详细

leetcode--Permutations(打印所有排列)

时间:2014-04-01 22:03:35      阅读:559      评论:0      收藏:0      [点我收藏+]

Problem Description:

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

思路分析:

利用递归性质,先固定一个数,然后对剩下的数进行排列,直到剩下最后一个数,形成一个排列,循环将当前数字与剩下的数依次交换后再递归,直到递归结束。

代码如下:

class Solution {
public:

    void swap(int &a,int &b)
    {
        int temp=a;
        a=b;
        b=temp;
    }
    
    void permutations(vector<int> num,int begin,vector<int> &permutation,vector<vector<int> > &res)
    {
        if(begin==num.size())
        {
            res.push_back(permutation);
            return;
        }
        for(vector<int>::size_type index=begin;index!=num.size();++index)
        {
            
            swap(num[begin],num[index]);
            permutation.push_back(num[begin]);
            permutations(num,begin+1,permutation,res);
            permutation.pop_back();
            swap(num[begin],num[index]);         
        }
    }

    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int> > res;
        if(num.empty())
            return res;
        vector<int> permutation;
        permutations(num,0,permutation,res);
        return res;
    }
};


leetcode--Permutations(打印所有排列),布布扣,bubuko.com

leetcode--Permutations(打印所有排列)

原文:http://blog.csdn.net/longhopefor/article/details/22752025

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!