77. Combinations

仅供自己学习

 

题目:

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Example 2:

Input: n = 1, k = 1
Output: [[1]]

Constraints:

1 <= n <= 20
1 <= k <= n



思路:

穷举所有满足题目条件的可能,考虑回朔法。和一般的回朔法的题大体是相同的。但是可以推一下剪枝的方法大大提高运行效率。

剪枝:针对此题,我们可以发现当一个数字和其他数字组合时会有组合得到数字数小于 k,所以组合后数字的数还小于k的组和就可以舍去不再去 DFS。

例如 n=4,k=3时,[1,3,4], 是最后一个,因为其后的组合[1,4]的大小已经小于K,所以诸如此类的组合都可舍去。设搜索起点的上届为x,即剪枝后能到的最大数,当前组合的数字的数量为 m。

则有公式 x = n -(k - m)+ 1, 对于 n=4,k=3的情况,当组合的数字数量为1的时候,x= 4-(3 -1)+1=3,即1,最大能和3组合,是满足的。

 

代码:

 1 class Solution {
 2 public:
 3     vector<vector<int>> combine(int n, int k) {
 4         vector<vector<int>> res;
 5         vector<int> out;
 6         backtracking(n,k,out,res,1);
 7         return res;
 8     }
 9     void backtracking(int n,int k,vector<int>& out,vector<vector<int>>& res,int start){
10         if(out.size() ==k){
11             res.push_back(out);
12             return;
13         }
14         for(int i=start;i<=n-(k-out.size())+1;++i){  //剪枝作用在此
15             out.push_back(i);
16             backtracking(n,k,out,res,i+1);
17             out.pop_back();
18         }
19     }
20 };

 

posted @ 2021-02-03 11:07  Mrsdwang  阅读(56)  评论(0)    收藏  举报