[笔试题]字符串的排列和组合
2014-09-22 21:41
204 查看
【代码】
C++ Code
C++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | /* version: 1.0 author: hellogiser blog: http://www.cnblogs.com/hellogiser date: 2014/9/22 */ #include "stdafx.h" #include "iostream" #include <vector> using namespace std; void print(char *str) { cout << str << endl; } void swap(char *a, char *b) { char t = *a; *a = *b; *b = t; } //====================================================== // string permutation // abc =======abc,acb,bac,bca,cab,cba //====================================================== void permutation(char *str, int len, int index) { if (index == len) { print(str); } else { for (int i = index; i < len; i++) { swap(str[index], str[i]); permutation(str, len, index + 1); swap(str[index], str[i]); } } } void Permutation(char *str) { if(str == NULL || *str == '\0') return; int len = strlen(str); permutation(str, len, 0); } //====================================================== // string combination // abc =========a,b,c,ab,ac,bc,abc //====================================================== void print(vector<char> &result) { vector<char>::iterator iter = result.begin(); for (; iter != result.end(); iter++) { cout << *iter; } cout << endl; } void combination(char *str, int m, vector<char> &result) { // exception for example C(1,2) if(str == NULL || *str == '\0' && m > 0) return; //base cases if (m == 0) { print(result); return; } //choose current char C(n-1,m-1) result.push_back(*str); combination(str + 1, m - 1, result); // not choose current char C(n-1,m) result.pop_back(); combination(str + 1, m, result); } void Combination(char *str) { if(str == NULL || *str == '\0') return; vector<char> result; int len = strlen(str); for (int i = 1; i <= len; i++) { combination(str, i, result); } } void test_permutation() { char str[] = "abc"; Permutation(str); } void test_combination() { char str[] = "abc"; Combination(str); } void test_main() { test_permutation(); cout << "==========================\n"; test_combination(); } int main(void) { test_main(); return 0; } /* abc acb bac bca cba cab ========================== a b c ab ac bc abc */ |
相关文章推荐
- [互联网面试笔试汇总C/C++-11] 字符串全排列和组合算法
- 排列组合,字符串——Killer Names
- 排列组合算法(微软笔试题:输出1到n的全排列)
- 字符串的排列与组合
- java 字符串排列组合
- 字符串的排列和组合代码 C++
- 字符串排列和组合的JAVA实现
- 字符串的排列和组合
- 字符串排列和组合的问题
- 【概率论与数理统计】-排列组合笔试题汇总
- 字符串排列组合
- 字符串的全排列和组合算法
- 字符串数组元素排列与组合
- 编程之法:字符串的排列组合
- 我理解的剑指offer----字符串的全排列和组合算法
- 笔试中常用的计算公式,排列与组合
- 字符串的排列与组合
- JAVA 输出指定字符串所有排列组合
- 面试28字符串的排列组合
- 【前端笔试】JavaScript实现字符串全排列