Combinations:给定数据范围与位数,求出

来源:互联网 发布:如何申请淘宝小号流程 编辑:程序博客网 时间:2024/06/05 18:39

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],]
思路:深度优先递归遍历,将结果存储下来即可。

    public void dfs(int index,int c,int n,int k,List<List<Integer>> list,int[] x){        if(c==k){            List<Integer> l = new ArrayList<Integer>();            for(int i = 0;i<n;i++){                if(x[i]!=0){                    l.add(i+1);                }            }            list.add(l);            return;        }else{            for(int i = index;i<n;i++){                x[i] = 1;                dfs(i+1,c+1,n,k,list,x);                x[i] = 0;            }        }    }       public List<List<Integer>> combine(int n, int k) {        int[] x = new int[n];        List<List<Integer>> list = new ArrayList<List<Integer>>();               dfs(0,0,n,k,list,x);               return list;    }




原创粉丝点击