您的位置:首页 > 其它

【算法】递归求解几类排列组合问题

2014-04-13 10:25 190 查看

一.全排列(递归)

#include <stdio.h>
#include <stdlib.h>

void permutation(char *str, char *begin) {
if (str==NULL || begin==NULL) return;

if (*begin == '\0')
printf("%s\n", str);
else {
char *pCh;
for (pCh=begin; *pCh!='\0'; pCh++) {
char temp = *pCh;
*pCh = *begin;
*begin = temp;

permutation(str, begin+1);
temp = *begin;
*begin = *pCh;
*pCh = temp;
}
}
}

int main()
{
char a[] = "abcd";
permutation(a, a);
return 0;
}


二.全排列(next_permutation)

#include <stdio.h>
#include <stdlib.h>

void swapTwo(char *n1, char *n2) {
char temp = *n1;
*n1 = *n2;
*n2 = temp;
}

int nextPemutation(char a[], int n) {
int item_head;
int item;
for (item=n-1; item>0; item--) {
if (a[item-1] < a[item])
break;
}

if (item == 0) return -1;

item_head = item - 1;
for (item=n-1; item>item_head; item--) {
if (a[item_head] < a[item])
break;
}

swapTwo(&a[item_head], &a[item]);

for (item=item_head+1; item<n; item++, n--) {
swapTwo(&a[item], &a[n-1]);
}

return 0;
}

int main() {
char a[] = "abcd";
while (nextPemutation(a, 4) >= 0) {
printf("%s\n", a);
}
return 0;
}


一.全排列(递归)

class Solution {

public:

vector<vector<int> > permuteUnique(vector<int> &num) {

vector<vector<int> > res;

if (num.empty())

return res;

sort(num.begin(), num.end());

res.push_back(num);

while (n_permute(num)) {

res.push_back(num);

}

return res;

}

bool n_permute(vector<int> &num) {

int item, head_item;

for (item=num.size()-1; item>0; item--) {

if (num[item-1] < num[item])

break;

}

if (item == 0)

return false;

else

head_item = item - 1;

int last = num.size()-1;

for (item=last; item>head_item; item--) {

if (num[head_item] < num[item])

break;

}

swap(num[head_item], num[item]);

for (int i=head_item+1; i<last; i++, last--) {

swap(num[i], num[last]);

}

return true;

}

};

class Solution {

public:

vector<vector<int> > subsets(vector<int> &S) {

vector<vector<int> > res;

if (S.empty())

return res;

sort(S.begin(), S.end());

for (int i=1; i<1<<S.size(); i++) {

combine(S, i, res);

}

vector<int> empty_temp;

res.push_back(empty_temp);

return res;

}

void combine(vector<int> &S, int m, vector<vector<int> > &res) {

vector<int> temp;

for (int i=0; i<S.size(); i++) {

if (m & (1 << i)) {

temp.push_back(S[i]);

}

}

res.push_back(temp);

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: