첫 번째 패키지가 조합에 포함되어 있다면 재귀를 "추측"하고 첫 번째 패키지없이 재귀 적으로 호출 할 수 있습니다.
의사 코드 :
combinations(packages, sol):
if (packages.length == 0): //base clause
print sol
return
package <- packages.first //1 possibility: the first package is in the combination
packages.removeFirst()
sol.append(package)
combinations(packages,sol) //recursively invoke without the first package
sol.removeLast() //clean up environment - remove the last added package
combinations(packages,sol) //2nd possibility: the first package is not in the combination
주 :
- 빈 용액은 [어떤 패키지를 선택하지 또한이 알고리즘의 실행 가능한 옵션으로 가정 - 그렇지 않은 경우 기본 절에서 쉽게 처리 할 수 있습니다.
- 순서가 중요하지 않은 것으로 가정합니다. Package1 AND Package2는 Package2 AND Package1과 동일합니다.
2^n
가능한 패키지를 chosing를위한 조합, 그래서 당신은 O(2^n)
시간이 필요합니다 [본 프로그램 포함]을 요청, 그래서 100 개 패키지와이 알고리즘을 호출하려고하지 않을 일을 어떤 알고리즘이 있습니다 ....
public static void printCombinations(LinkedList<String> packages, LinkedList<String> sol) {
if (packages.size() == 0) {
System.out.println(sol);
return;
}
String pack = packages.poll(); //also removes the head
sol.addLast(pack);
printCombinations(new LinkedList(packages),sol);
sol.removeLast();
printCombinations(new LinkedList(packages),sol);
}
및 invokation는 것입니다 : 자바에서
,이 같은 것을 볼 수 있었다
printCombinations(packages, new LinkedList<String>());
여기서 packages
은 모든 패키지가 포함 된 LinkedList
입니다.
- 나는
packages
에 대한 LinkedList
을 사용하고 난 그게 더 명확 찾아 때문에 새 개체를 만들었습니다. 성능을 향상 시키려면배열을 index
[회귀 호출간에 변경] 순서로 사용하면 packages
이 여러 번 반복되는 것을 피할 수 있습니다.
지금까지 가지고있는 것을 보여주세요. – RBarryYoung