1. Given a sequence without repeated numbers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2 ],
[3,2,1]
]
First think about the template:
public void dfs(int k){
if (k==nums.length){
System.out.println(tmp); //排列完毕 打印。
return;
}
for(int i=0;i<nums.length;i++ ){
tmp.set(k,nums[i]); //从第0位开始依次赋值
dfs(k+1);
}
}
Write the following code
import java.util.*;
class Solution {
List<List<Integer>> res;
List<Integer> tmp = new ArrayList<>();
boolean[] used ;
public List<List<Integer>> permute(int[] nums) {
used = new boolean[nums.length]; //初始化
for(int i=0;i<used.length;i++){
used[i] =false;
tmp.add(0);
}
res = new ArrayList<>();
dfs(0, nums);
return res;
}
public void dfs(int k, int[] nums) { //套模板
if (k == nums.length) {
res.add(new ArrayList<>(tmp)); //注意这里
return;
}
for (int i = 0; i < nums.length; i++) {
if (!used[i]) {
tmp.set(k,nums[i]);
used[i] = true;
dfs(k + 1, nums);
used[i] = false;
}
}
}
}
Read the solution to a problem back thinking : The main difference in the code is almost the same here :()
// tmp.add(0); 注释掉
public void dfs(int k, int[] nums) { //套模板
if (k == nums.length) {
res.add(new ArrayList<>(tmp));
System.out.println("out" + tmp);
return;
}
for (int i = 0; i < nums.length; i++) {
if (!used[i]) {
tmp.add(nums[i]);
used[i] = true;
dfs(k + 1, nums);
used[i] = false;
tmp.remove(tmp.size()-1); //回溯 还原状态
}
}
}
2. Full arrangement II
Given a sequence nums that can contain repeated numbers, return all non-repeated permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Thinking is different from the above,
Method 1: You can directly de-duplicate in res
Method 2: Sort first and pruning when backtracking. The solution can be referred to: backtracking pruning
if (used[i])
continue;
if(i>0 &&nums[i]==nums[i-1]&&!used[i-1]) //如果相等,且前一个没有使用
continue;
3、
Given two integers n and k , return all possible combinations of k numbers in 1... n .
Example:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
public class Solution {
List<List<Integer>> res;
List<Integer> tmp = new ArrayList<>();
public static void main(String[] args) {
Solution s = new Solution();
s.combine(4,2);
}
public List<List<Integer>> combine(int n, int kk) {
res = new ArrayList<>();
if (kk <= 0 || n < kk) {
return res;
}
dfs(1,kk,n);
return res;
}
public void dfs(int b,int kk,int n) { //套模板
if (tmp.size()==kk) {
res.add(new ArrayList<>(tmp));
System.out.print(tmp);
return;
}
for (int i = b; i <=n; i++) {
tmp.add(i);
dfs(i+1,kk,n); //这里的不同点是i+1 不是上面排列中的k [[1, 2][1, 3][1, 4][2, 3][2, 4][3, 4]]
// 如果改成上面排列中的的k(也就是改成b+1) [[1, 2][1, 3][1, 4][2, 2][2, 3][2, 4][3, 2][3, 3][3, 4][4, 2][4, 3][4, 4]]
// 改成b [[1, 1][1, 2][1, 3][1, 4][2, 1][2, 2][2, 3][2, 4][3, 1][3, 2][3, 3][3, 4][4, 1][4, 2][4, 3][4, 4]]
tmp.remove(tmp.size()-1);
}
}
}