0002算法笔记——排列问题整数划分问题Hanoi问题.docxVIP

  • 0
  • 0
  • 约2.73千字
  • 约 5页
  • 2023-05-10 发布于湖北
  • 举报

0002算法笔记——排列问题整数划分问题Hanoi问题.docx

递归的概念想必大家都清楚,概念神马的直接略过。这里介绍递归相关的几个问题。 1、排列问题 ii设R={r1,r2,...,rn}是要进行排列的n 个元素,Ri=R-{ri}。集合 x 中元素的全排列记为Perm(X)。(r)Perm(X)表示在全排列Perm(X)的每一个排列前加上前缀r 得到的排列。R 的全排列可归纳如下: i i 当n=1 时,Perm(R)=(r),其中r 是集合中唯一的元素; 当n1 时,Perm(R)由(r )Perm(R ),(r )Perm(R ),(r )Perm(R )。。。。 1 1 2 2 3 3 (r )Perm(R )构成。 n n 程序代码: [cpp] view plain copy [cpp] view plain copy 1. 2. 3. 4. 5. 6. 7. 8. 9. //2-4 排列问题 #include stdafx.h #include iostream using namespace std; template class Type inline void Swap(Type a,Type b); template class Type 10. void Perm(Type list[],int k,int m); 11. 12. int main() 13. { 14. 15. 16. 17. int list[3]; for(int i=0; i3;i++) { list[i] = i+1; 运行结果:18.19. 运行结果: 18. 19. 20. 21. } 22. } Perm(list,0,2); return 0; template class Type inline void Swap(Type a,Type b) 25. { 26. 27. 28. 29. } 30. Type temp = a; a = b; b = temp; template class Type void Perm(Type list[],int k,int m) 33. { 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. } //只剩下一个元素 if(k == m){ for(int i=0; i=m; i++) { coutlist[i] ; } coutendl; } else { //将 list[k:m}中的每一个元素分别与 list[k]中的元素交换 //然后递归计算 list[k+1:m]的全排列,将计算结果作为 list[0:k]后缀 for(int i=k; i=m;i++){ Swap(list[k],list[i]); Perm(list,k+1,m); Swap(list[k],list[i]); } } 2、整数划分问题 将正整数n 表示成一系列正整数之和,n=n +n +n +......n (其中, 1 2 3 k n =n =. n =1,k=1),正整数n 的这种表示称为正整数n 的划分。 1 2 k 正整数n 的不同划分个数称为正整数n 的划分数,记作p(n)。例如:正整数 6 有 11 总不同的划分 6; 5+1; 4+2,4+1+1; 3+3,3+2+1,3+1+1+1; 2+2+2,2+2+1+1,2+1+1+1+1; 1+1+1+1+1+1; 1记q(n,m)为正整数n 的所有不同划分中,最大加数n 不大于m 的划分个数。可以建立如下递推关系: 1 前面三个递推式比较好理解,关键是第四个递推式。当nm1 时,n 的划分由两部分组成。以整数q(6,3)为例,q(n,m-1)内容是第 5 排和第 6 6 排内容,不大于 2 的 6 的划分;q(n-m,m)内容是第 4 排,不大于 3 的 (6-3=3)的划分。 程序代码: [cpp] view plain copy [cpp] view plain copy 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. //2-4 整数划分问题 #include stdafx.h #include iostream using namespace std; int q(int n,int m); int main(){ coutq(6,6)endl; return 0; 11. } 12. 13. int q(int n,int m) 14. { 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. } if( n1 || m1) { return 0; }

文档评论(0)

1亿VIP精品文档

相关文档