Combinations

来源:互联网 发布:三菱plc编程电缆 编辑:程序博客网 时间:2024/06/03 13:17

Q:

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],]

Solution:

Note: We need to remove the last added element from the list, since we need a room to try new numbers.

public class Solution {    List<List<Integer>> combines;public List<List<Integer>> combine(int n, int k) {        combines = new ArrayList<List<Integer>>();        if (n <= 0 || k <= 0 || n < k)            return combines;        for (int i = 1; i <= n-k+1; i++) {        ArrayList<Integer> list = new ArrayList<Integer>();        subCombine(i, n, k, list);        }        return combines;    }     public void subCombine(int start, int end, int k, ArrayList<Integer> list) {        list.add(start);        if (list.size() == k) {        List<Integer> addlist = new ArrayList<Integer>(list);        combines.add(addlist);        return;        }        for (int i = start+1; i <= end; i++) {        subCombine(i, end, k, list);        list.remove(list.size()-1);        }    }}


0 0
原创粉丝点击