[LeetCode-interview algorithm classic-Java implementation] [077-Combinations (number of Combinations)], leetcode -- java
[077-Combinations (number of Combinations )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
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],]
Theme
Given two numbers n and k, calculate all the combinations of k numbers in 1-n.
Solutions
The Recursive Divide and conquer method is used for solving the problem. For details, see the code.
Code Implementation
Algorithm Implementation class
Import java. util. arrayList; import java. util. collections; import java. util. using list; import java. util. list; public class Solution {private List <Integer> result; private List <Integer> l; public List <Integer> combine (int n, int k) {result = new partition list <> (); if (n> 0 & k> 0 & n> = k) {l = new partition list <> (); combine (1, n, k);} return result ;} /*** determine the combination ** @ param start the start position of the number to be selected * @ param end the end position of the number to be selected * @ param num at [start, number of numbers selected in end] */private void combine (int start, int end, int num) {if (num = 0) {List <Integer> tmp = new ArrayList <> (); for (Integer I: l) {tmp. add (I);} result. add (tmp); return;} int endFirst = end-num + 1; // The maximum value available for the first number for (int I = start; I <= endFirst; I ++) {l. add (I); combine (I + 1, end, num-1); l. remove (new Integer (I ));}}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting at http://blog.csdn.net/derrantcm/article/details/47142961]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.