combination
Title description: Given two integers
n
andk
, return all possiblek
numbers in the[1, n]
You can press any order return the answer.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/combinations/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: dfs (depth first traversal)
Declare two global variables as the result set (result) and the current path (path), and add a depth-first traversal method. The specific logic of the method is as follows:
- When
k=0
, that is, the current path already has k numbers, it means that the current path meets the conditions and is added to the result set;- Then traverse the numbers starting from 1, recursively call the dfs method, and remove the last number of the current path from the path after the call.
Finally, the returned result set is all the combinations that meet the conditions.
import java.util.ArrayList;
import java.util.List;
public class LeetCode_077 {
/**
* 结果集
*/
private static List<List<Integer>> result = new ArrayList<>();
/**
* 当前的路径
*/
private static List<Integer> path = new ArrayList<>();
/**
* dfs
*
* @param n 总共有n个数
* @param k k个数的组合
* @return
*/
public static List<List<Integer>> combine(int n, int k) {
// 递归方法入口
dfs(1, n, k);
// 返回结果集
return result;
}
/**
* 深度优先搜索
*
* @param u 路径的起点
* @param n 总共有n个数
* @param k 还剩多少个值达到原定的k个数
*/
private static void dfs(int u, int n, int k) {
if (k == 0) {
/**
* 当k等于0时,表示已经有k个数了,满足条件放入结果集中
*/
result.add(new ArrayList<>(path));
return;
}
for (int i = u; i <= n - k + 1; i++) {
/**
* 将当前的数添加到路径中
*/
path.add(i);
dfs(i + 1, n, k - 1);
path.remove(path.size() - 1);
}
}
public static void main(String[] args) {
for (List<Integer> integers : combine(4, 2)) {
for (Integer integer : integers) {
System.out.print(integer + " ");
}
System.out.println();
}
}
}
[Daily Message] Don't be afraid of worry, just do it when you think about it. This world is like this. When you don't dare to realize your dream, your dream will be farther and farther away from you. When you are brave to pursue your dream, The whole world will come to help you.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。