欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode-77-Combinations

发布时间:2025/7/25 编程问答 53 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。