LeetCode77: 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],
]
Hide Tags Backtracking
Given a number n, evaluate the combination of all k numbers between 1 and n.
You can draw a sketch on the paper, which can be solved recursively. The recursive termination condition is k = 0. Because the combination needs to be saved to the set vector, backtracking is also required to save the data.
Runtime: 8 ms
class Solution {public: vector
> combine(int n, int k) { vector
> result; vector
vec; helper(1,n,k,vec,result); return result; } void helper(int first,int last,int k,vector
& vec,vector
> & result) { if(k==0) { result.push_back(vec); return ; } for(int i=first;i<=last-k+1;i++) { vec.push_back(i); helper(i+1,last,k-1,vec,result); vec.pop_back(); } }};