Problem:
Given-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], [up], [1,3], [1,4],]
Hide TagsBacktrackingTest instructions: All permutation combinations of k numbers for output 1~n
Thinking:
(1) See the problem should think of using Dfs deep search method
(2) The difficulty of deep search is how to deal with the next step, here open a K-size array, record the deep search every step to get the number
(3) The time complexity is O (k*n), the space complexity is O (K)
Code
Class Solution {private: vector<vector<int> > ret; Vector<int> tmp;public: vector<vector<int> > Combine (int n, int k) { ret.clear (); Tmp.resize (k); DFS (1,n,k,1); return ret; } Protected: void dfs (int dep, int n, int k,int start) { if (dep>k) { ret.push_back (TMP); return; } for (int i=start;i<=n;i++) { tmp[dep-1]=i; DFS (dep+1,n,k,i+1);}} ;
Leetcode | | 77, combinations