int[] arr = {1, 2, 3}
sub array 必须是连续的元素,比如{1}, {1,2}, {1,2,3},不能有{1,3}
sub sequence or subset 中元素可以不连续, 比如{1,3}
permutation意思为排列,元素出现顺序不同即为不同permutation
combination意思为组合,元素出现顺序不同也可以为同一个组合
import java.util.ArrayList;
import java.util.List;
public class SubarrayAndSubSequenceAndPermutation {
public static void main(String[] args) {
int[] arr = {1,2,3};
//generate all the subarrays
List<List<Integer>> li = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
List<Integer> temp = new ArrayList<>();
for (int j = i; j < arr.length; j++) {
temp.add(arr[j]);
li.add(new ArrayList<>(temp));
}
}
System.out.println(li);
//subsequence Or Combination!!!!!!!!!
List<List<Integer>> subsequence = new ArrayList<>();
generateSubSequence(subsequence, new ArrayList<>(), arr, 0);
System.out.println(subsequence);
List<List<Integer>> permutationList = new ArrayList<>();
generatePermutation(permutationList, new ArrayList<>(), arr);
System.out.println(permutationList);
}
//store the index of element in orginal array in case there are redundent elements in the array
private static void generatePermutation(List<List<Integer>> permutationList, ArrayList<Integer> temp, int[] arr) {
if (temp.size() == arr.length) {
List<Integer> tempList = new ArrayList<>();
for (int i : temp) {
tempList.add(arr[i]);
}
permutationList.add(new ArrayList(tempList));
} else {
for (int i = 0; i < arr.length; i++) {
if (!temp.contains(i)) {
temp.add(i);
generatePermutation(permutationList, temp, arr);
temp.remove(temp.size() - 1);
}
}
}
}
private static void generateSubSequence(List<List<Integer>> subsequence, ArrayList<Integer> temp, int[] arr, int start) {
subsequence.add(new ArrayList(temp));
for (int i = start; i < arr.length; i++) {
temp.add(arr[i]);
generateSubSequence(subsequence, temp, arr, i + 1);
temp.remove(temp.size() - 1);
}
}
}