"077-combinations (number of combinations)""leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"Original Question
Given-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],]
Main Topic
Given two numbers n and K, all combinations of k numbers from 1-n are obtained.
Thinking of solving problems
The method of recursive division is used to solve the problem, see Code.
Code Implementation
Algorithm implementation class
ImportJava.util.ArrayList;ImportJava.util.Collections;ImportJava.util.LinkedList;ImportJava.util.List; Public class solution { Privatelist<list<integer>> result;PrivateList<integer> l; PublicList<list<integer>>Combine(intNintK) {result =NewLinkedlist<> ();if(N >0&& k >0&& N >= k) {L =NewLinkedlist<> (); Combine1, N, K); }returnResult }/** * for combination * * @param start selectable number of start positions * @param End of selectable number of positions * @param Num number selected in [Start, end] * / Private void Combine(intStartintEndintNUM) {if(num = =0) {list<integer> TMP =NewArraylist<> (); for(Integer i:l) {tmp.add (i); } result.add (TMP);return; }intEndfirst = End-num +1;//The maximum value that can be selected for the first number for(inti = start; I <= Endfirst; i++) {l.add (i); Combine (i +1, End, Num-1); L.remove (NewInteger (i)); } }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special InstructionsWelcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47142961"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "077-combinations (number of combinations)"