/**
* 功能:有个马戏团正在设计叠罗汉的表演节目,一个人要站在另一个人的肩膀上。出于实际和美观的考虑,在上面的人一定要比下面的人矮一点、轻一点。
* 已知马戏团每个人的身高和体重,计算叠罗汉最多能够叠几个人。
*/
[java] view plain copy
- /**
- * 思路:去掉细枝末节,真正的题目是:给定一个列表,每个元素由一对项目组成。找出最长的子序列,其中第一项和第二项均以非递减的顺序排列。
- * 1、子问题:最长递增子序列:找出以元素i结尾的最长递增子序列。
- * 以A[i]结尾的最长子序列可以通过检查先前全部解法得出,只要将A[i]附加到最长且“有效”的那个序列即可。有效指A[i]>list.tail的任意序列。
- * 2、真正的子问题;最长递增子序列,每个元素均为一对数据。
- * @param items
- * @return
- */
- public static ArrayList<Actor> getIncreasingSequence(ArrayList<Actor> items){
- Collections.sort(items);
- return longestIncreasingSubsequence(items);
- }
- public static ArrayList<Actor> longestIncreasingSubsequence(ArrayList<Actor> array) {
- // TODO Auto-generated method stub
- ArrayList<Actor>[] solutions=new ArrayList[array.size()];
- longestIncresingSubsequence(array,solutions,0);
- ArrayList<Actor> bestSequence=new ArrayList<Actor>();
- for(ArrayList<Actor> sol:solutions){
- bestSequence=seqWithMaxLength(bestSequence,sol);
- }
- return bestSequence;
- }
- public static void longestIncresingSubsequence(ArrayList<Actor> array,ArrayList<Actor>[] solutions, int currentIndex) {
- // TODO Auto-generated method stub
- if(currentIndex>=solutions.length||currentIndex<0)
- return;
- Actor currentElement=array.get(currentIndex);
- //找出可以附加currentElement的最长子序列
- ArrayList<Actor> bestSequence=new ArrayList<Actor>();
- for(int i=0;i<currentIndex;i++){
- if(array.get(i).isBefore(currentElement))
- bestSequence=seqWithMaxLength(bestSequence, solutions[i]);
- }
- //附加currentElement
- ArrayList<Actor> newSolution=new ArrayList<Actor>();
- if(bestSequence!=null)
- newSolution.addAll(bestSequence);
- newSolution.add(currentElement);
- //加入到列表中,然后递归
- solutions[currentIndex]=newSolution;
- longestIncresingSubsequence(array, solutions, currentIndex+1);
- }
- //返回较长的序列
- public static ArrayList<Actor> seqWithMaxLength(ArrayList<Actor> seq1, ArrayList<Actor> seq2) {
- // TODO Auto-generated method stub
- if(seq1==null)
- return seq2;
- if(seq2==null)
- return seq1;
- return seq1.size()>seq2.size()?seq1:seq2;
- }
[java] view plain copy
- class Actor implements Comparable{
- int height;
- int weight;
- @Override
- public int compareTo(Object s) {
- // TODO Auto-generated method stub
- Actor second=(Actor) s;
- if(this.height!=second.height)
- return ((Integer)this.height).compareTo(second.height);
- else
- return ((Integer)this.weight).compareTo(second.weight);
- }
- public boolean isBefore(Actor other){
- if(this.height<other.height&&this.weight<other.weight)
- return true;
- return false;
- }
- }