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
Return to I = 1, and then I ++
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
Return to I = 2, and then I ++
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
Return to I = 3, and then I ++
I is 4 now. Adding 4 I = 5 first is invalid. End the for loop.
Then remove 4
Return to 4, and then I ++
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)