题目:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
代码:
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; if (n < k) return res; int ori_k = k; if (k > n / 2) k = n - k; set<set<int>> cur_res; set<int> tmp; cur_res.insert(tmp); for (int i = 0; i < k; i++) { set<set<int>> update_res; for (set<set<int>>::iterator iter = cur_res.begin(); iter != cur_res.end(); iter++) { for (int j = 1; j <= n; j++) { set<int> cbnt = *iter; cbnt.insert(j); if (cbnt.size() == i + 1) { update_res.insert(cbnt); } } } cur_res = update_res; } if (ori_k != k) { set<int> total; for (int i = 1; i <= n; i++) total.insert(i); set<set<int>> update_res; for (set<set<int>>::iterator iter = cur_res.begin(); iter != cur_res.end(); iter++) { set<int> cur = *iter; set<int> cplm = total; for (set<int>::iterator jter = cur.begin(); jter != cur.end(); jter++) { cplm.erase(*jter); } update_res.insert(cplm); } cur_res = update_res; } for (set<set<int>>::iterator iter = cur_res.begin(); iter != cur_res.end(); iter++) { set<int> cur_set = *iter; vector<int> cur_nums; for (set<int>::iterator jter = cur_set.begin(); jter != cur_set.end(); jter++) { cur_nums.push_back(*jter); } res.push_back(cur_nums); } return res; } };