题解 | #牛群分组#
牛群分组
https://www.nowcoder.com/practice/6fc6122a10314bb584741155e639039c?tpId=363&tqId=10605848&ru=/exam/oj&qru=/ta/super-company23Year/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D363
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型二维数组
*/
private static ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
public int[][] subsets (int[] nums) {
ArrayList<Integer> tempList = new ArrayList<>();
boolean [] isSelected = new boolean[nums.length];
backTrack(tempList, 0, nums, isSelected);
int [][] result = new int[arrayList.size()][];
for (int i = 0; i < arrayList.size(); i++) {
ArrayList<Integer> arrayList1 = arrayList.get(i);
int [] temp = new int [arrayList1.size()];
for (int j = 0; j < arrayList1.size(); j++) {
temp[j] = arrayList1.get(j);
}
result[i] = temp;
}
return result;
}
public void backTrack(ArrayList<Integer> tempList, int start, int [] nums,
boolean [] isSelected) {
arrayList.add(new ArrayList<>(tempList));
for (int i = start; i < nums.length; i++) {
if (i != start && nums[i] == nums[i - 1]) {
continue;
}
if (!isSelected[i]) {
tempList.add(nums[i]);
isSelected[i] = true;
backTrack(tempList, i + 1, nums, isSelected);
isSelected[i] = false;
tempList.remove(tempList.size() - 1);
}
}
}
}
本题知识点分析:
1.递归
2.回溯
3.数学模拟
4.集合存取和集合转数组
本题解题思路分析:
1.因为要编号可能重复,进行去重判断
2.如果元素没有被选择过,那么就添加到临时集合,标记为true,然后递归下一个元素,传入start = i+1
3.递归出来后,取消选择过,然后从临时集合移除最后一个元素
本题使用编程语言: Java
如果你觉得本篇对你有帮助的话,可以点个赞支持一下,感谢~

