gpt4 book ai didi

java - 为 LIst 中的元素创建子序列

转载 作者:行者123 更新时间:2023-12-02 00:45:13 28 4
gpt4 key购买 nike

我正在使用下面的代码创建大小为 2 的唯一子序列。如何创建不同大小的子序列。大小是动态的。

例如,[1 2 3 4] -> [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3 , 4]]

对于尺寸 3,将为 , [[1, 2, 3], [1, 2, 4], [2, 3, 4]]

public static int getTheSubseq(List<Integer> AList){
List<List<Integer>> li = new ArrayList<>();

for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
List<Integer> temp = new ArrayList<>();
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);

}
}
System.out.println(li);
return 1;

}

最佳答案

使用递归,您可以构建子序列,如下所示:

private void buildSubsequence( List<Integer> source, int targetSize,
List<List<Integer>> result, Stack<Integer> currentSubsequence, int currentIndex ) {

//We don't want to iterate beyond the point where we can't build a complete subsequence.
//Thus we'll need to subtract the number of still needed elements
//(target count - number of elements already in the subsequence - 1 for this call)
int maxIndex = source.size() - ( targetSize - currentSubsequence.size() - 1);

//iterate over each index from the current one to this call's max
for( int i = currentIndex; i < maxIndex; i++ ) {

//add the element at that index to the subsequence
currentSubsequence.push( source.get( i ) );

//if we're done make a copy
if( currentSubsequence.size() == targetSize ) {
result.add( new ArrayList<Integer>( currentSubsequence) );
} else { //if we're not done, get the next element
buildSubsequence( source, targetSize, result, currentSubsequence, i + 1 );
}

//remove the last element added by push() to have it replaced with the next one
currentSubsequence.pop();
}
}

然后你这样调用它:

List<Integer> source = Arrays.asList( 1,2,3,4,5,6 );
List<List<Integer>> result = new LinkedList<>();

buildSubsequence( source, 3, result, new Stack<>(), 0 );

这将创建以下子序列:

[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 2, 6]
[1, 3, 4]
[1, 3, 5]
[1, 3, 6]
[1, 4, 5]
[1, 4, 6]
[1, 5, 6]
[2, 3, 4]
[2, 3, 5]
[2, 3, 6]
[2, 4, 5]
[2, 4, 6]
[2, 5, 6]
[3, 4, 5]
[3, 4, 6]
[3, 5, 6]
[4, 5, 6]

请注意,这只是解决该问题的一种方法。 :)

关于java - 为 LIst 中的元素创建子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905904/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com