[LeetCode]Combinations
Combinations
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], ]
深搜,递归,回溯。这是一类题,举一反三。
1 class Solution { 2 public: 3 void dfs(int n,int k,int start,vector<int>&tmp,vector<vector<int>>& result) 4 { 5 if(tmp.size()==k) 6 { 7 result.push_back(tmp); 8 } 9 for(int i=start;i<=n;i++) 10 { 11 tmp.push_back(i); 12 dfs(n,k,i+1,tmp,result); 13 tmp.pop_back(); 14 } 15 } 16 vector<vector<int>> combine(int n, int k) { 17 vector<int> tmp; 18 vector<vector<int>> result; 19 if(n<1 ||(k>n)) return result; 20 dfs(n,k,1,tmp,result); 21 return result; 22 } 23 };