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

Permutations

时间:2014-06-04 19:10:16      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

bubuko.com,布布扣
class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) 
    {
        bool used[num.size()];
        for(int i=0;i<num.size();i++)
            used[i]=false;
        vector<vector<int> > result;
        vector<int> possible;
        for(int i=0;i<num.size();i++)
            possible.push_back(0);
        gen(result,num,used,0,possible);
        return result;
    }
    void gen(vector<vector<int> >& result,vector<int>& num,bool* used,int step,vector<int>& possible)
    {
        if(step==num.size())
        {
            result.push_back(possible);
            return;
        }
        
        for(int i=0;i<num.size();i++)
        if(!used[i])
        {
            used[i]=true;
            possible[step]=num[i];
            gen(result,num,used,step+1,possible);
            used[i]=false;
        }
    }
}; 
bubuko.com,布布扣

Permutations,布布扣,bubuko.com

Permutations

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759362.html

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