算法描述:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
解题思路:题目要求给出所有肯能的组合,首先想到了回溯法。需要注意的是下一次迭代的起始是i+1,这样去除之前用过的数。
vector<vector<int>> combine(int n, int k) { vector<vector<int>> results; vector<int> temp; backtracking(results, temp, n, k, 1); return results; } void backtracking(vector<vector<int>>& results, vector<int>& temp, int n, int k, int index){ if(temp.size() == k){ results.push_back(temp); return; } for(int i=index; i <= n; i++){ temp.push_back(i); backtracking(results, temp, n , k, i+1); temp.pop_back(); } }