LeetCode Combinations

来源:互联网 发布:淘宝宝贝详情模板代码 编辑:程序博客网 时间:2024/06/03 17:16

Description:

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

Solution:

排列组合,也是前面已经用到过的方法,用DFS来解决。

注意提一点,组合因为是有一个特殊要求,即为选出的点有且仅有k个,所以每一层的循环要特别当心,当前这个DFS层所能选取的点的范围应当是[currentIndex+1, n+1-(k-count) ],利用循环的范围来保证,当我的currentIndex走到n+1也就是结尾的时候,count与k相等。只不过这里最终提交,利用系统栈会爆栈,所以为了简洁,就先用了count==k的结束标记。

参数说明:currentIndex当前已经到了第几个数字的下标,count是已经选了几个数字的个数,currentList是记录了当前选出了那几个数字,count=currentList.size(),n和k则是和题目中所给的一样。

import java.util.*;public class Solution {List<List<Integer>> list;public List<List<Integer>> combine(int n, int k) {list = new ArrayList<List<Integer>>();dfs(0, 0, new ArrayList<Integer>(), n, k);return list;}void dfs(int currentIndex, int count, ArrayList<Integer> currentList,int n, int k) {// if (currentIndex == n + 1) {if (count == k) {list.add(new ArrayList(currentList));return;} else {for (int i = currentIndex + 1; i <= n + 1 - (k - count); i++) {currentList.add(i);dfs(i, count + 1, currentList, n, k);currentList.remove(currentList.size() - 1);}}}}




0 0
原创粉丝点击