46. permutations
This question gives an array, we can call it nums and nums has distinct integers, and then it require to return all the possible permutations, which mean you can return the answer in any order. For example,
Q: how many results in this case?
because nums has three distinct integers, so there will be 321 = 6 results, I mean there will 6 results, right?
Idea:
code:
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> rs = new ArrayList<>();
int length = nums.length;
boolean[] used = new boolean[nums.length];
List<Integer> path = new ArrayList<>();
dfs(nums,used,rs,path);
return rs;
}
public void dfs(int[] nums, boolean[] used, List<List<Integer>> rs,List<Integer> path) {
/*
if(depth==nums.length) {
rs.add(new ArrayList<>(path));
return;
}
*/
if(path.size()==nums.length) {
rs.add(new ArrayList<>(path));
return;
}
// 在非叶子结点处,产生不同的分支,
// 这一操作的语义是:在还未选择的数中依次选择一个元素作为下一个位置的元素,
// 这显然得通过一个循环实现。
for(int i=0;i<nums.length;i++) {
if(!used[i]) {
path.add(nums[i]);
used[i]=true;
System.out.println(" 递归之前 => " + path);
dfs(nums,used,rs,path); // 继续递归填下一个数
used[i]=false;
path.remove(path.size()-1); // 先进后出 = 后进先出
System.out.println("递归之后 => " + path);
}
}
}
public static void main(String[] args) {
System.out.print(new demo46().permute(new int[] {1,2,3}));
/*
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
*/
}
77. Combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].
You may return the answer in any order. For example
Q: how many results in this case?
because we can select 2 distinct integers from range [1,4], so there will be
C
4
2
=
6
C_{4}^2=6
C42=6 results, I mean there will 6 results, right?
1 difference:
- [1,2], [2,1] is the same result
Idea:
code:
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> rs = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int start=1;
dfs(n,k,start,rs,path);
return rs;
}
public void dfs(int n, int k,int start,List<List<Integer>> rs,List<Integer> path) {
/*
if(depth==k) {
rs.add(new ArrayList<>(path));
return;
}
*/
if(path.size()==k) {
rs.add(new ArrayList<>(path));
return;
}
for(int i=start;i<=n;i++) {
path.add(i);
dfs(n,k,i+1,rs,path);
path.remove(path.size()-1);
}
}
public static void main(String[] args) {
System.out.print(new demo77().combine(4,2));
/*
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
*/
}