Combinations

来源:互联网 发布:apache tika使用说明 编辑:程序博客网 时间:2024/06/11 13:29

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

用到回溯,DFS

思路是,首先,这是一道排列组合的题,需要从1~n的数字中选择k个数字,容易想到的是利用回溯法,每次加入一个元素,然后向后面找可能的情况。

写DFS的套路应该是首先要有一个变量表示当前的位置,这道题里curIndex指代的是目前到哪一位。然后,开始构思如何建立递归的写法。

写DFS的套路一般是:先写出终止条件, 然后写递归的过程,一般是需要先添加元素,然后调用自己,进一步往深处递归下去,然后当递归结束向上返回的时候,再删除当前层的元素。

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



0 0