当前位置:   article > 正文

C语言 | Leetcode C语言题解之第40题组合总和II

C语言 | Leetcode C语言题解之第40题组合总和II

题目:

题解:

  1. int** ans;
  2. int* ansColumnSizes;
  3. int ansSize;
  4. int* sequence;
  5. int sequenceSize;
  6. int** freq;
  7. int freqSize;
  8. void dfs(int pos, int rest) {
  9. if (rest == 0) {
  10. int* tmp = malloc(sizeof(int) * sequenceSize);
  11. memcpy(tmp, sequence, sizeof(int) * sequenceSize);
  12. ans[ansSize] = tmp;
  13. ansColumnSizes[ansSize++] = sequenceSize;
  14. return;
  15. }
  16. if (pos == freqSize || rest < freq[pos][0]) {
  17. return;
  18. }
  19. dfs(pos + 1, rest);
  20. int most = fmin(rest / freq[pos][0], freq[pos][1]);
  21. for (int i = 1; i <= most; ++i) {
  22. sequence[sequenceSize++] = freq[pos][0];
  23. dfs(pos + 1, rest - i * freq[pos][0]);
  24. }
  25. sequenceSize -= most;
  26. }
  27. int comp(const void* a, const void* b) {
  28. return *(int*)a - *(int*)b;
  29. }
  30. int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) {
  31. ans = malloc(sizeof(int*) * 2001);
  32. ansColumnSizes = malloc(sizeof(int) * 2001);
  33. sequence = malloc(sizeof(int) * 2001);
  34. freq = malloc(sizeof(int*) * 2001);
  35. ansSize = sequenceSize = freqSize = 0;
  36. qsort(candidates, candidatesSize, sizeof(int), comp);
  37. for (int i = 0; i < candidatesSize; ++i) {
  38. if (freqSize == 0 || candidates[i] != freq[freqSize - 1][0]) {
  39. freq[freqSize] = malloc(sizeof(int) * 2);
  40. freq[freqSize][0] = candidates[i];
  41. freq[freqSize++][1] = 1;
  42. } else {
  43. ++freq[freqSize - 1][1];
  44. }
  45. }
  46. dfs(0, target);
  47. *returnSize = ansSize;
  48. *returnColumnSizes = ansColumnSizes;
  49. return ans;
  50. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/476310
推荐阅读
相关标签
  

闽ICP备14008679号