[LeetCode] Combinations

简介: A typical backtracking problem. For any backtracking problem, you need to be think about three ascepts: What is a partial solution and when is it fi...

A typical backtracking problem. For any backtracking problem, you need to be think about three ascepts:

  1. What is a partial solution and when is it finished? --- In this problem, the partial solution is a combination (sol). It is finished once it contains k elements.
  2. How to find all the partial solutions? --- In the following code, I simply traverse all the possible starting elements (start).
  3. When to make recursive calls? --- In the following code, once an element is added to the partial solution, we call the function to generate the remaining elements recursively.

Of course, remember to recover to the previous status once a partial solution is done. In the following code, line 18 (sol.pop_back()) is for this purpose.

The following should be self-explanatory :)

 1 class Solution {
 2 public:
 3     vector<vector<int>> combine(int n, int k) {
 4         vector<vector<int> > res;
 5         vector<int> sol;
 6         combination(1, n, k, sol, res);
 7         return res;
 8     }
 9 private:
10     void combination(int start, int n, int k, vector<int>& sol, vector<vector<int> >& res) {
11         if (k == 0) {
12             res.push_back(sol);
13             return;
14         }
15         for (int i = start; i <= n; i++) {
16             sol.push_back(i);
17             combination(i + 1, n, k - 1, sol, res);
18             sol.pop_back();
19         }
20     }
21 };

 

目录
相关文章
[LeetCode]--17. Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:D
1324 0
LeetCode - 17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个数字串,输出其在手机九宫格键盘上的所有可能组合.
936 0
[LeetCode] Letter Combinations of a Phone Number
Well, a typical backtracking problem. Make sure you are clear with the following three problems: What is a partial solution and when is it finished?...
926 0