Topic:
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],]
Thought: Backtracking method
Constructs an auxiliary function, Combine_helper.
(1) Recursion once, fill in a number
(2) Fill in the number, cannot be less than the current number of values, to prevent duplication
(3) Backtracking: Pop_back () The last number added, back to the previous level
(4) The end condition, when the number is filled with k number, the current completed, backtracking.
About the specific implementation of backtracking, this article has an animation, explained very vivid: backtracking
Attention:
1. Note that the number we fill in must be incremented, otherwise it will result in duplicate numbers.
2. Grasp the essence of retrospective thinking. Pop_back is critical. Go back to the previous level.
Complexity: non-deterministic polynomial time complexity class, NP problem
AC Code:
Class Solution {public: vector<vector<int> > Combine (int n, int k) { vector<vector<int> > ret; if (n = = 0 | | k = = 0 | | n < k) return ret; vector<int> tmp; Combine_helper (0, 0, N, K, TMP, ret); return ret; } Private: void Combine_helper (int start, int num, int n, int k, vector<int> tmp, vector<vector<int> > & ret) { if (num = = k) { ret.push_back (TMP); return; } for (int i = start; i < n; i++) { tmp.push_back (i+1); Combine_helper (i+1, Num+1, N, K, TMP, ret); Tmp.pop_back ();}} ;
[C + +] leetcode:83 combinations (backtracking method)