【Leetcode】Combinations

来源:互联网 发布:hadoop java 源码下载 编辑:程序博客网 时间:2024/06/05 21:57

题目链接:https://leetcode.com/problems/combinations/

题目:

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

For example,
If n = 4 and k = 2, a solution is:

[  [2,4],  [3,4],  [2,3],  [1,2],  [1,3],  [1,4],]

思路:

经典组合问题。

算法:

int k = 0;List<List<Integer>> iLists = new ArrayList<List<Integer>>();List<Integer> list = new ArrayList<Integer>();int n = 0;public List<List<Integer>> combine(int n, int k) {this.n = n;this.k = k;dspComb(0);return iLists;}void dspComb(int cur) {if (list.size() == k) {iLists.add(new ArrayList<Integer>(list));} else {for (int i = cur; i < n; i++) {list.add(i + 1);dspComb(i + 1);list.remove(list.size() - 1);}}}


0 0
原创粉丝点击