[Leetcode] combinations

Source: Internet
Author: User

Given two integersNAndK, Return all possible combinationsKNumbers out of 1...N.

For example,
IfN= 4 andK= 2, a solution is:

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

Search for a forest using DFS. During the search, the child value must be greater than the parent node value for pruning. The forest is in the following shape:

Suppose n = 4, K = 2;

The Code is as follows:

 1 public class Solution { 2     private void comb(int n,int k,int level,List<List<Integer>> answer,List<Integer> result){ 3         if(level == k){ 4             ArrayList<Integer> temp = new ArrayList<Integer>(result); 5             answer.add(temp); 6              7             return; 8         } 9         for(int i = 1;i <= n;i++){10             if(result.isEmpty() || result.get(result.size()-1) < i){11                 result.add(i);12                 comb(n, k, level+1, answer, result);13                 result.remove(result.size()-1);14             }15         }16     }17     public List<List<Integer>> combine(int n, int k) {18         List<List<Integer>> answer = new ArrayList<List<Integer>>();19         List<Integer> result = new ArrayList<Integer>();20         21         comb(n, k, 0, answer, result);22         23         return answer;24     }25 }

Level records the current search level. If K is equal, a combination is found.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.