全排列

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

 

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;
    }
};

 

posted @ 2014-09-10 23:27  jihite  阅读(308)  评论(0编辑  收藏  举报