Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the combination problem of LeetCode

Shulou Source: shulou.com Published: 2022-06-01 13:08:05 09月26日 Update

This article mainly introduces LeetCode how to solve the combination problem, the article is very detailed, has a certain reference value, interested friends must read it!

Title

Given two integers n and k, return 1. The combination of all possible k numbers in n.

Example: input: n = 4, k = 2 output: [[2List temp 4], [3 int 4], [2jue 3], [1jue 2], [1d3], [1d4],] code class Solution {List temp = new ArrayList (); List ans = new ArrayList (); public List combine (int n, int k) {dfs (1, n, k); return ans } public void dfs (int cur, int n, int k) {/ / pruning: if the length of temp plus the length of interval [cur, n] is less than k, it is impossible to construct temp if (temp.size () + (n-cur + 1) < k) {return of length k. } / / record the legal answer if (temp.size () = = k) {ans.add (new ArrayList (temp)); return;} / / consider selecting the current location temp.add (cur); dfs (cur + 1, n, k); temp.remove (temp.size ()-1) / / consider not selecting the current location dfs (cur + 1, n, k);}}

The above is all the content of the article "how to solve the combination problem in LeetCode". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Combination length question location content article selection legal two number code value interest interval boy partner integer more knowledge example Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker macOS Redmi OPPO Reno MySQL