Getting Started with the Blue Bridge Cup (26) Combination Problems (Backtracking Algorithm)

-----Continue to update the Spring Getting Started series of articles-----

If you also like Java and algorithms, welcome to subscribe to the column to learn and communicate together!

Your likes, attention, and comments are the driving force for my creation!

-------I hope my article is helpful to you-------

Column: Blue Bridge Cup Series

 

1. Topic description

Given two integers nand k, [1, n]return all possible kcombinations of numbers in the range .

You can return answers 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]]

2. Problem-solving ideas

1. The routine of this question is compared to selecting different groups of data according to a certain number from a bunch of numbers. When the value of k is small, it can be completed using conventional violent methods, but if the value of k is too large, it is impossible for us to write dozens of layers of loops Come on, shall we?

2. Therefore, the backtracking algorithm is adopted, that is, the method of combining loop and recursion . In fact, this question is similar to a tree structure, the loop is responsible for horizontal traversal, and recursion is for vertical traversal!

 

 3. Code implementation

class Solution {
    LinkedList<Integer>path=new LinkedList<>();//保存子集
    List<List<Integer>> result=new ArrayList<>();//结果集
    public List<List<Integer>> combine(int n, int k) {
        combineHelper(n,k,1);
        return result;

    }
    public void combineHelper(int n,int k,int start)
    {
        if (k==path.size()) {
            result.add(new ArrayList<>(path));//满足个数,加入结果集
            return;
        }
        for (int i=start;i<=n-(k- path.size())+1;i++)
        {
            path.add(i);//加入子集
            combineHelper(n,k,i+1);
            path.removeLast();
        }
    }
}

 

It's not easy to post, I implore the big guys to raise your hands!


Likes: Likes are a kind of virtue, and they are the recognition of my creation by the bosses!


Comments: There is no white contact, it is the beginning of communication between you and me!


Collection: May you pick more, it is the appreciation of the bosses to me!

Guess you like

Origin blog.csdn.net/m0_55278347/article/details/129403090