码迷,mamicode.com
首页 > 其他好文 > 详细

回溯法---子集和问题(6)

时间:2015-05-26 20:28:17      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

回溯法---子集和问题(6)
问题描述:

在给定的集合中挑选出所有和为C的子集和。

在(2)的算法框架基础上:

import java. util.Vector ;

public class Subset extends CombineProblem {

         int[] arr ;

         int c;

         public Subset(int[] arr , int c, int n) {

                 this.flag = false ;

                 this.n = n;

                 this.x = new Integer[n];

                 this.arr = arr;

                 this.c = c;

         }

        @Override
         public Vector<Comparable> makeIterm (int k) {
                Vector vec = new Vector();
                 for ( int i = 0 ; i <= 1 ; i++) {
                        vec .add( i);
                 }
                 return vec;
         }

        @Override
         public boolean complete(int k) {
                 int sum = 0 ;
                 if ( k >= n)
                         for ( int i = 0 ; i < n; i++) {
                                sum += ( arr[i ] * (Integer) x [i]);
                         }
                 return sum == c;
         }

        @Override
         public void printsolution(int k) {
                 for ( int i = 0 ; i < n; i++) {
                         if (( Integer) x [i] == 1) {
                                System .out. print(arr [i] + " ");
                         }
                 }
                System .out. println("" );
         }

        @Override
         public boolean isPartial(int k) {
                 int sum = 0 ;
                 for ( int i = 0 ; i < k; i++)
                        sum += ( arr[i ] * (Integer) x [i]);
                 return sum <= c;
         }
}

主函数:

public class Main {

         public static void main(String [] args) {

                int[] arr = { 1 , 2 , 3 , 4 , 5 , 6 , - 1, -3, -5 };

                Problem p = new Subset(arr , 6 , arr. length);

                p .explore(0);

                if (! p.flag) {
                   System .out. println("no solution!" );
                }

         }

}

输出结果:

6
2 4
1 5
1 2 3 




回溯法---子集和问题(6)

标签:

原文地址:http://www.cnblogs.com/ZhangJinkun/p/4531357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!