【算法】递归求解几类排列组合问题
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);
}
};
相关文章推荐
- 算法笔记之 全排列算法 一 递归求解
- 算法之使用递归求解迷宫问题
- 递归求解几类排列组合问题(四、普通选择性组合排列)
- 递归求解整数划分问题 分类: 算法 2014-09-25 21:37 158人阅读 评论(0) 收藏
- 字符串相似度算法 递归与动态规划求解分析
- 递归求解几类排列组合问题(五、生成全子集组合排列)
- 算法笔记之 全排列算法 一 递归求解
- 递归求解几类排列组合问题(四、普通选择性组合排列)
- 递归求解几类排列组合问题(六、非重复生成全子集组合排列)
- 经典算法1:递归求解汉诺塔
- 经典算法2:递归求解整数划分
- 第一篇:算法之使用递归求解迷宫问题
- 求最大子数组的和,算法导论之分治递归求解,暴力求解,记忆扫描方法。
- 经典算法——递归求解汉诺塔
- java经典算法_030猴子分桃(递归求解)
- 第五篇:算法之使用递归求解全排列
- 【算法】 递归求解整数划分
- 字符串相似度算法 递归与动态规划求解分析
- 递归求解几类排列组合问题(一、类循环组合排列)
- 一个数组算法题,利用递归-回溯求解