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],
]
  1. 本题与Combinations Sum类似,都是用回溯法。求1...n中k个数的不同组合,很明显我们需要注意的就是每个数字只能出现一次,这点与Combinations Sum不同。

  2. 代码

 public class Solution {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        int num=0;
        public List<List<Integer>> combine(int n, int k) {
            num=n;
            if(n==0||k==0) return res;
            combineHelper(1,k,new ArrayList<Integer>());
            return res;
        }
        private void combineHelper(int index,int count,List<Integer> pre){
            if(count==0){
                res.add(pre);
                return;
            }
            for(int i=index;i<=num;i++){
                List<Integer> cur=new ArrayList<Integer>(pre);
                cur.add(i);
                combineHelper(i+1,count-1,cur);
            }
        }
    }

tiffanytown
6 声望2 粉丝

keep learning