leetcode : Combinations
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], ]
AC代码:
class Solution { public: vector<vector<int> > combine(int n, int k) { return c(n,k); } vector<vector<int>> c(int n, int k){ vector<vector<int>> ret; if(k == 0){ vector<int> temp; ret.push_back(temp); return ret; }else if(n == k){ vector<int> temp; for(int i = 0; i < n; ++i) temp.push_back(i + 1); ret.push_back(temp); return ret; }else{ ret = c(n - 1,k); auto temp = c(n - 1,k - 1); for(auto &w : temp){ w.push_back(n); ret.push_back(w); } return ret; } } };
浙公网安备 33010602011771号