Same algorithm with combination. Input as the (1..n), constraint is that the length of each combine should be k.
1 class Solution { 2 public: 3 void getComb(vector<vector<int> > &result, vector<int> current, int n, int k, int start) { 4 if (current.size() == k) { 5 result.push_back(current); 6 return; 7 } 8 for (int i = start; i <= n; i++) { 9 current.push_back(i); 10 getComb(result, current, n, k, i+1); 11 current.pop_back(); 12 } 13 } 14 vector<vector<int> > combine(int n, int k) { 15 vector<vector<int> > result; 16 getComb(result, vector<int> (), n, k, 1); 17 return result; 18 } 19 };
时间: 2024-10-12 13:26:16