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:
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]Analysis:
Another classic DFS problem. Once we see "all possible" key words, we need to consider using DFS idea.
Two things to think about:
1) Avoid duplicates - we use a int st to avoid choosing the same combination again. In other words, we only choose the numbers larger than current numbers.
2) Choose k numbers - we decrease k each time we choose a number.
Code:
class Solution { public: vector<vector<int> > combine(int n, int k) { vector<vector<int> > outv; if (k==0 || n<k) return outv; vector<int> res; recur(outv, res, n, k, 0); return outv; } void recur(vector<vector<int>> &outv, vector<int> &res, int n, int k, int st) { if (k==0) { outv.push_back(res); return; } for (int i=st; i<n; i++) { res.push_back(i+1); recur(outv, res, n, k-1, i+1); res.pop_back(); } return; } };
No comments:
Post a Comment