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

全排列

时间:2014-09-10 23:49:41      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   2014   

dd

#include <iostream>
using namespace std;
void swap(char *a, char *b) 
{     
    char tmp;     
    tmp = *a;     
    *a = *b;     
    *b = tmp; 
}  
void perm(char list[], int beg, int end) 
{     
    if(beg > end)     
    {          
        for(int i = 0; i <= end; i++)             
            cout << list[i];
        cout << endl;
    }     
    else     
    {         
        for(int i = beg; i <= end; i++)         
        {             
            swap(&list[i], &list[beg]);             
            perm(list, beg + 1, end);             
            swap(&list[i], &list[beg]);         
        }     
    } 
} 
int main() 
{     
    char list[] = {1, 2, 3};     
    int lens = sizeof(list) / sizeof(*list);
    perm(list, 0, lens-1);     
    return 0; 
}

dd

#include <iostream>
#include <vector>
using namespace std;
void getPer(vector<int> &num, int index, 
        vector<int> &tmp, vector<vector<int > > &rev)
{
    if (index == num.size())
        rev.push_back(tmp);
    for (int i = index; i < num.size(); ++i)
    {
        swap(num[i], num[index]);
        tmp.push_back(num[index]);
        getPer(num, index+1, tmp, rev);
        tmp.pop_back();
        swap(num[i], num[index]);
    }
}
vector<vector<int> > permute(vector<int> &nums)
{
    vector<vector<int> > rev;
    vector<int> tmp;
    getPer(nums, 0, tmp, rev);
    return rev;
}

int main()
{
    vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vector<vector<int> > rev = permute(vec);
    cout << rev.size() << endl;
}

dd

bubuko.com,布布扣

 

class Solution {
public:
    void getPermute(vector<int> &num, int index, vector<int> &tmp, vector<vector<int> > &result)
    {
        if (index == num.size())
            result.push_back(num);
        for (int i = index; i < num.size(); ++i)
        {
            swap(num[i], num[index]);
            tmp.push_back(num[index]);
            getPermute(num, index+1, tmp, result);
            tmp.pop_back();
            swap(num[i], num[index]);
        }
    }
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int> > result;
        vector<int> tmp;
        getPermute(num, 0, tmp, result);
        return result;
    }
};

 

全排列

标签:style   blog   http   color   io   os   ar   for   2014   

原文地址:http://www.cnblogs.com/kaituorensheng/p/3963534.html

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