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], ]
典型暴力搜尋題,一共有n種可能,對於每個元素i,即可以放入結果中,又可以不放入結果中,
注意搜尋時剪枝,即每種結果有k個值,大於k個的剪掉即可
class Solution { public: typedef vector<vector<int> > VectorArray; int m_n,m_k; VectorArray result; vector<int> solution; void dfs(int level){ if( solution.size() == m_k){ result.push_back(solution); return; } for(int i = level; i <= m_n; ++ i){ solution.push_back(i); dfs(i+1); solution.pop_back(); } } VectorArray combine(int n, int k){ m_n = n, m_k = k; dfs(1); return result; } };