Total Accepted: 69360 Total Submissions: 206274 Difficulty: Medium
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],]
Subscribe to see which companies asked this question
Hide TagsBacktrackingHide Similar Problems(m) combination Sum (m) permutations
Analysis:
The typical backtracking method
Class Solution {public: void Dfs (Vector<vector<int > > &ans, vector<int> &subans, int Start, int n, int k) { if (subans.size () = = k)//have obtained the answer, and backtrack { ans.push_back (Subans); return;//Backtracking } for (int i = start; I <= n; i++) { subans.push_back (i); DFS (ans, subans, i + 1, n, k); Subans.pop_back (); Backtrack minus end element } } vector<vector<int> > combine (int n, int k) { vector<vector<int > > result; if (N < k | | k = = 0) return result; Vector<int> Subres; DFS (result, subres, 1, N, k); return result;} ;
Note: This blog post is Ebowtang original and may continue to be updated later in this article. If reproduced, please make sure to copy this article information!
Original address: http://blog.csdn.net/ebowtang/article/details/50835803
Original Author Blog: Http://blog.csdn.net/ebowtang
This blog leetcode key index: http://blog.csdn.net/ebowtang/article/details/50668895
<leetcode oj> 77. Combinations