题目描述:
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:[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]
解题思路:
1 class Solution { 2 public: 3 vector> combine(int n, int k) { 4 vector > result; 5 vector elem; 6 7 combine(n, k, 1, result, elem); 8 return result; 9 }10 private:11 void combine(int n, int k, int cur, vector > &result, vector &elem) {12 if (elem.size() == k) {13 result.push_back(elem);14 return;15 }16 17 for (int i = cur; i <= n; ++i) {18 elem.push_back(i);19 combine(n, k, i + 1, result, elem);20 elem.pop_back();21 }22 }23 };