字符串的排列组合问题
2013-03-16 20:32
351 查看
1.字符串的排列
2.字符串的组合
问题3:打靶问题。一个射击运动员打靶,靶一共有10环,连开10 枪打中90环的可能性有多少?
思路:这道题的思路与字符串的组合很像,用递归解决。一次射击有11种可能,命中1环至10环,或脱靶。
Ref:http://www.cnblogs.com/GoAhead/archive/2012/05/30/2526563.html
#include <string> #include <iostream> using namespace std; void permulation_solution1(char *pStr, int begin, int end) { if (begin == end - 1) cout<<pStr<<endl; else { for (int i = begin; i < end; i++) { swap(pStr[i], pStr[begin]); permulation_solution1(pStr, begin+1, end); swap(pStr[i], pStr[begin]); } } } int main() { char pStr[] = "abcd"; permulation_solution1(pStr, 0 , 4); }
2.字符串的组合
#include <iostream> #include <vector> using namespace std; void combination_m(char *pStr, int m, vector<char> &result) { if (pStr == NULL || (*pStr == '\0' && m != 0)) return ; if (m == 0) { for (vector<char>::iterator it = result.begin(); it != result.end(); it++) { cout<<*it<<" "; } cout<<endl; return; } result.push_back(*pStr); combination_m(pStr+1, m-1, result); result.pop_back(); combination_m(pStr+1, m, result); } void combinnation(char *pStr) { if (pStr == NULL || *pStr == '\0') { return; } int number = strlen(pStr); for (int i = 1; i <= number; i++) { vector<char> result; combination_m(pStr, i, result); } } int main() { char pStr[] = "abc"; combinnation(pStr); }
问题3:打靶问题。一个射击运动员打靶,靶一共有10环,连开10 枪打中90环的可能性有多少?
思路:这道题的思路与字符串的组合很像,用递归解决。一次射击有11种可能,命中1环至10环,或脱靶。
/函数功能 : 求解number次打中sum环的种数 //函数参数 : number为打靶次数,sum为需要命中的环数,result用来保存中间结果,total记录种数 //返回值 : 无 #include <iostream> #include <vector> using namespace std; void shootProblem_Solution1(int number, int sum, vector<int> &result, int* total)//此处total传递的应该为指针! { if (sum < 0 || number*10 < sum) return; if (number == 1) { if (sum <= 10) { for (vector<int>::iterator it = result.begin(); it < result.end(); it++) { cout<<*it<<" "; } cout<<sum<<endl; (*total)++; } else return; } for (int i = 0; i <= 10; i++) { result.push_back(i); shootProblem_Solution1(number-1, sum-i, result, total); result.pop_back(); } } void shootProblem(int number, int sum) { int total = 0; vector<int> result; shootProblem_Solution1(number, sum, result, &total); cout<<"total sum="<<total<<endl; } int main() { shootProblem(10,90); }
Ref:http://www.cnblogs.com/GoAhead/archive/2012/05/30/2526563.html
相关文章推荐
- 分解让复杂问题简单化-面试题28-字符串的排列与组合
- java实现字符串排列组合问题
- 解题笔记(21)——字符串的排列组合问题
- 字符串的全排列和组合递归非递归--排列组合扩展问题
- 字符串排列组合问题
- 字符串的排列组合问题-java
- 解题笔记(21)——字符串的排列组合问题
- 字符串的排列组合问题
- 字符串的排列组合问题
- 海涛老师的面试题-作业28-字符串的排列组合问题。
- 字符串的排列组合问题
- 字符串的排列组合问题
- 字符串的排列组合问题
- java实现字符串排列组合问题
- 字符串的排列组合问题
- 字符串排列和组合的问题
- 字符串的排列与组合及八皇后等其他相关问题
- 字符串的全排列和所有组合问题
- 面试100题系列之5字符串的排列组合问题
- 解题笔记(21)——字符串的排列组合问题