[Leetcode] Combinations

た 入场券 2021-12-03 07:21 351阅读 0赞

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

For example,
If n = 4 and k = 2, a solution is:

  1. [
  2. [2,4],
  3. [3,4],
  4. [2,3],
  5. [1,2],
  6. [1,3],
  7. [1,4],
  8. ]

DFS!

  1. 1 class Solution {
  2. 2 public:
  3. 3 void getNextComb(vector<vector<int> > &res, vector<int> v, int n, int k, int idx) {
  4. 4 if (idx > n) {
  5. 5 return;
  6. 6 }
  7. 7 v.push_back(idx);
  8. 8 if (v.size() == k) {
  9. 9 res.push_back(v);
  10. 10 }
  11. 11
  12. 12 getNextComb(res, v, n, k, idx + 1);
  13. 13 v.pop_back();
  14. 14 getNextComb(res, v, n, k, idx + 1);
  15. 15 }
  16. 16
  17. 17 vector<vector<int> > combine(int n, int k) {
  18. 18 vector<vector<int> > res;
  19. 19 vector<int> v;
  20. 20 int idx = 1;
  21. 21 getNextComb(res, v, n, k, idx);
  22. 22 return res;
  23. 23 }
  24. 24 };

转载于:https://www.cnblogs.com/easonliu/p/3639553.html

发表评论

表情:
评论列表 (有 0 条评论,351人围观)

还没有评论,来说两句吧...

相关阅读