1.输出和为一个给定整数的所有组合,例如 n=5 ;5=1+4;5=2+3(相加的数不能重复);则输出 1,4;2,3。

  1. #include<iostream>
  2. using namespace std;
  3. int main(void)
  4. {
  5. unsigned long int i,j,k;
  6. cout << "please input the number" << endl;
  7. cin >> i;
  8. if( i % 2 == 0)
  9. j = i / 2;
  10. else
  11. j = i / 2 + 1;
  12. cout << "The result is" << endl;
  13. for(k = 0; k < j; k++)
  14. cout << i << "=" << k << "+" << i-k << endl;
  15. return 0;
  16. }

image.png

2.递规反向输出字符串的例子,可谓是反序的经典例程

  1. #include<iostream>
  2. void inverse(char *p)
  3. {
  4. if (*p == '\0')
  5. return;
  6. inverse(p+1);
  7. printf("%c", *p);
  8. }
  9. int main(int argc, char *argv[])
  10. {
  11. inverse("abc\0");
  12. return 0;
  13. }

image.png

3、写一段程序,找出数组第K大小的数,输出数所在的位置。例如{2,4,3,4,7}中,第一大的数是7,位置在4。第二大、第三大的数都是4,位置在1、3随便输出哪一个均可。

函数接口为:int find_orderk(const int* narry,const int n,const int k)
要求算法复杂度不能是 O(n^2)

  1. #include <iostream>
  2. using namespace std;
  3. int Partition(int*L, int low, int high)
  4. {
  5. int temp = L[low];
  6. int pt = L[low];
  7. while (low < high)
  8. {
  9. while (low < high && L[high] >= pt)
  10. --high;
  11. L[low] = L[high];
  12. while (low < high && L[low] <= pt)
  13. ++low;
  14. L[low] = temp;
  15. }
  16. L[low] = temp;
  17. return low;
  18. }
  19. void QSort(int*L, int low, int high)
  20. {
  21. if (low < high)
  22. {
  23. int pl = Partition(L, low, high);
  24. QSort(L, low, pl - 1);
  25. QSort(L, pl + 1, high);
  26. }
  27. }
  28. int main()
  29. {
  30. int narry[100], addr[100];
  31. int sum = 1, t;
  32. cout << "Input number:" << endl;
  33. cin >> t;
  34. while (t != -1)
  35. {
  36. narry[sum] = t;
  37. addr[sum - 1] = t;
  38. sum++;
  39. cin >> t;
  40. }
  41. sum -= 1;
  42. QSort(narry, 1, sum);
  43. for (int i = 1; i <= sum; i++)
  44. cout << narry[i] << '\t';
  45. cout << endl;
  46. int k;
  47. cout << "Please input place you want:" << endl;
  48. cin >> k;
  49. int aa = 1;
  50. int kk = 0;
  51. for (;;)
  52. {
  53. if (aa == k)
  54. break;
  55. if (narry[kk] != narry[kk + 1])
  56. {
  57. aa += 1;
  58. kk++;
  59. }
  60. }
  61. cout << "The NO." << k << "number is:" << narry[sum - kk] << endl;
  62. cout << "And it's place is:";
  63. for (int i = 0; i < sum; i++)
  64. {
  65. if (addr[i] == narry[sum - kk])
  66. cout << i << '\t';
  67. }
  68. return 0;
  69. }