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], ]
class Solution { public: vector<vector<int>> res; vector<vector<int>> combine(int n, int k) { vector<int> temp; BFS(temp,n,1,k); return res; } void BFS(vector<int> &temp,int n,int cur,int k) //cur(1~n) { if(temp.size()==k) //如果长度为k,则返回结果 { res.push_back(temp); return; } for(int i=cur;i<=n;i++) //遍历cur后到n的元素 { vector<int> tmp=temp; tmp.push_back(i); BFS(tmp,n,i+1,k); } } };
原文:http://blog.csdn.net/u011391629/article/details/52125690