[笔试题]字符串的排列和组合
【代码】
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 */ |