Advertisement
AbsolutelyS

recursion

May 11th, 2024
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. // 1
  2.  
  3. /*
  4. * Returns the binomial coefficient n "choose" k
  5. * MUST BE RECURSIVE
  6. */
  7. int nChooseK(int n, int k) {
  8. if (k == 0 || k == n) {
  9. return 1;
  10. } else {
  11. return nChooseK(n - 1, k - 1) + nChooseK(n - 1, k);
  12. }
  13. }
  14.  
  15.  
  16. // 2
  17.  
  18. /*
  19. * You must find recursively the number of ways that a given integer can be expressed as the sum
  20. * of the unique, natural numbers.
  21. *
  22. * Example: the number of ways to get the number 6 by combining unique natural numbers is 4.
  23. * 1) 1 + 5 = 6
  24. * 2) 2 + 4 = 6
  25. * 3) 6 = 6
  26. * 4) 1 + 2 + 3 = 6
  27. */
  28.  
  29. int powerSumHelper(int n, int start) {
  30. if (n == 0) return 1;
  31. if (n < 0 || start > n) return 0;
  32.  
  33. int x = powerSumHelper(n - start, start + 1);
  34. int y = powerSumHelper(n, start + 1);
  35. return x + y;
  36. }
  37.  
  38. int powerSum(int n) {
  39. return powerSumHelper(n, 1);
  40. }
  41.  
  42.  
  43. // 3
  44.  
  45. #include <iostream>
  46. using namespace std;
  47.  
  48. void move(int disk, char source, char destination) {
  49. cout << "Move disk " << disk << " from rod " << source << " to rod " << destination << endl;
  50. }
  51.  
  52. void towersOfHanoi(int n, char source, char destination, char auxiliary) {
  53. if (n == 1) {
  54. move(n, source, destination);
  55. return;
  56. }
  57.  
  58. towersOfHanoi(n - 1, source, auxiliary, destination);
  59. move(n, source, destination);
  60. towersOfHanoi(n - 1, auxiliary, destination, source);
  61. }
  62.  
  63. // int main() {
  64. // // cout << powerSum(6) << endl;
  65. // // cout << powerSum(8) << endl;
  66. // towersOfHanoi(3, 'A', 'C', 'B');
  67.  
  68. // return 0;
  69. // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement