# [Leetcode] combinations (backtracking)

Source: Internet
Author: User

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],]`
This is a classic NP problem.

I starts from 1,

Add 1 first, then 2 temp = [1, 2]

Then remove 2 and 3 temp = [1, 3]

Then remove 3 and 4 temp = []

Then remove the 4 I = 5 invalid and end the for loop.

Then remove 1

I is now 2

Add 2 first, then 3 temp = [2, 3]

Then remove 3 and 4 temp = [2, 4]

Then remove the 4 I = 5 invalid and end the for loop.

Remove 2

I is 3 now

Add 3 first and then 4 temp = [3, 4]

Then remove the 4 I = 5 invalid and end the for loop.

Remove 3

I is 4 now. Adding 4 I = 5 first is invalid. End the for loop.

Then remove 4

I is now 5 and the end of the For Loop

End all

`public ArrayList<ArrayList<Integer>> combine(int n, int k) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();ArrayList<Integer> temp = new ArrayList<Integer>();if (n <= 0 || k < 0)return result;helper(n, k, 1, temp, result);return result;}public void helper(int n, int k, int startNum, ArrayList<Integer> temp,ArrayList<ArrayList<Integer>> result) {if (k == temp.size()) {result.add(new ArrayList<Integer>(temp));return;}for (int i = startNum; i <= n; i++) {temp.add(i);helper(n, k, i + 1, temp, result);temp.remove(temp.size() - 1);}}`
Why temp. Remove? To protect the field, you must know that the return statement can only restore the value before I, but cannot change the value in temp.

[Leetcode] combinations (backtracking)

Related Keywords:

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.