LeetCode problem solution --77: Combination

Related topics

Topic Link

LeetCode China, https://leetcode-cn.com/problems/combinations/ . Note need to log in.

Title Description

Given two integers  n  and  k , ... return. 1  possible all  k  combination number.

Examples

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Topic analysis

Analysis of the meaning of problems

The combination of mathematics. That list  \binom{k}{n} all possible.

A standard template DFS title, entry-level difficulty.

Sample data analysis

A little, no need for special analysis.

Algorithm thinking

K selected from small to large numbers, so the answer must be determined. There are several aspects of the details.

Search termination condition

Termination condition must be searched digits reaches k.

Search function parameters

1, an array, indicating that you are searching out a few numbers.

2, an integer number representing start to begin the search.

3, a represents an integer number n to terminate the search. This can be represented by the global variable, global variable if this parameter can be omitted.

4, leaving a few numbers need to search left.

Thus, the function prototype to this question dfs () may be expressed as follows:

//参数1:path存放已经搜索出了几个数据
//参数2:start表示从哪个数字开始搜索
//参数3:n表示搜索的最大数据
//参数4:left还剩下几个数没有搜索到
void dfs(vector<int> &path, int start, int n, int left);

Start calling way

//从0开始搜索,搜索到数据n,一共搜索k个数字
dfs(path, 0, n, k);

Backtracking

        path.push_back(i);//将数据i保存到path中
        dfs(path, i+1, n, k-1);
        path.pop_back();//回溯

AC reference code

class Solution {
public:
    vector<vector<int>> ans;//答案
 
    vector<vector<int>> combine(int n, int k) {
        vector<int> path;
 
        dfs(path, 1, n, k);
 
        return ans;
    }
 
    void dfs(vector<int> &path, int start, int n, int k) {
        if (0==k) {
            //搜索到了
            ans.push_back(path);
            return;
        }
 
        for (int i=start; i<=n; i++) {
            //加入当前数据
            path.push_back(i);
            dfs(path, i+1, n, k-1);
            path.pop_back();//回溯
        }
    }
};

 

Published 239 original articles · won praise 291 · Views 1.07 million +

Guess you like

Origin blog.csdn.net/justidle/article/details/104931818