LeetCode-77-Combinations
生活随笔
收集整理的这篇文章主要介绍了
LeetCode-77-Combinations
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
算法描述:
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();}}
转载于:https://www.cnblogs.com/nobodywang/p/10344792.html
总结
以上是生活随笔为你收集整理的LeetCode-77-Combinations的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: UiBot Creator v1.2火热
- 下一篇: 学生时代的最后一个新年,请一定要做这五件