Leetcode 77. Combinations
来源:互联网 发布:声场模拟软件 编辑:程序博客网 时间:2024/06/05 04:53
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],
]
s思路:
1. for+recursive:backtracking 或者dfs
class Solution {public: void helper(vector<vector<int>>&res,vector<int>&cur,int k,int n,int num){ if(k==0){res.push_back(cur);return;} for(int i=num;i<=n-k+1;i++){ cur.push_back(i); helper(res,cur,k-1,n,i+1); cur.pop_back(); } } vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; vector<int> cur; helper(res,cur,k,n,1); return res; }};//优化了,不用push_back()和pop_back,改用[]访问。class Solution {public: void helper(vector<vector<int>>&res,vector<int>&cur,int k,int n,int num,int pos){ // if(pos==k){res.push_back(cur);return;} for(int i=num;i<=n;i++){ cur[pos]=i; helper(res,cur,k,n+1,i+1,pos+1); } } vector<vector<int>> combine(int n, int k) { // vector<vector<int>> res; vector<int> cur(k,0); helper(res,cur,k,n-k+1,1,0); return res; }};
0 0
- LeetCode 77. Combinations
- [LeetCode]77.Combinations
- LeetCode --- 77. Combinations
- [Leetcode] 77. Combinations
- [leetcode] 77.Combinations
- leetCode 77.Combinations (组合)
- [leetcode] 77. Combinations
- 77. Combinations LeetCode
- <LeetCode OJ> 77. Combinations
- [LeetCode]77. Combinations
- leetcode 77. Combinations
- LeetCode *** 77. Combinations
- leetcode 77. Combinations
- LeetCode 77. Combinations
- LeetCode-77.Combinations
- LeetCode 77.Combinations
- [LeetCode]problem 77. Combinations
- [LeetCode] 77. Combinations
- content问题:a标签的颜色
- C++封装继承多态总结
- web安全之token
- 博客
- Spring MVC 执行流程和源码分析
- Leetcode 77. Combinations
- 1044. 火星数字(20)
- 240. Search a 2D Matrix II**
- Unity 框架
- 《HelloGitHub月刊》第10期
- IdleTask 详解
- 各种 Tool
- HttpSession对象的生命周期
- Cocos2dx 框架