zoukankan      html  css  js  c++  java
  • [置顶] 最近面试的算法题目

    一个集合x有都不相同的n个元素,使用这个集合中的不定个数的元素,组成一个和为s的序列,求出所有符合的序列,元素可以重复使用,只要元素的个数相同不考虑顺序。

    比如集合是x={2,3,4,5,7}; n=5, s=12可以得出以下的序列:

    2       2       2       2       2       2
    2       2       2       2       4
    2       2       2       3       3
    2       2       3       5
    2       2       4       4
    2       3       3       4
    2       3       7
    2       5       5
    3       3       3       3
    3       4       5
    4       4       4
    5       7

    
    


    #include <iostream>
    #include <vector>
    using namespace std;
    int PushVector(int *x,int n,int s,vector<int> &tablelist,int Position)
    {
    	if(s<0)
    	{
    		tablelist.clear();
    		return 0;
    	}
    	else if(s==0)
    	{
    		for(int i=0;i<tablelist.size();i++)
    		{
    			cout<<tablelist[i]<<"	";
    		}
    		cout<<"
    ";
    		
    		return 0;
    	}
    	else if(s>0)
    	{
    		for(int i=Position;i<n;i++)
    		{
    			vector<int> newtablelist;
    			for (int j=0;j<tablelist.size();j++)
    			{
    				newtablelist.push_back(tablelist[j]);
    			}
    			newtablelist.push_back(x[i]);
    			int news = s-x[i];
    			//cout<<i<<","<<news<<"
    ";
    			PushVector(x,n,news,newtablelist,i);
    		}
    
    
    	}
    	else
    	{
    
    
    	}
    	return 0;
    }
    
    
    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    int FindResult(int * x,int n,int s)
    {
    	vector<int> tablelist;
    	tablelist.clear();
    	PushVector(x,n,s,tablelist,0);
    	return 0;
    }
    
    
    
    
    int main(int argc, char** argv) 
    {
    	int x[]= {2,3,4,5,7};
    	int n =5;
    	int s=12;
    	FindResult(x,n,s);
    	system("pause");
    	return 0;
    }


    下面附上截图:


    好了这就是我们的全部解法,这个问题就是一个递归遍历的问题。

  • 相关阅读:
    Perl 简介(适合对 C 语言有点认识的读者)
    ASP.NET中的随机密码生成
    office2003下的EXCEL中英文图表名的对应
    css布局定位系列 (转)
    使用.Net访问Office编程接口
    在.NET 2.0 中发送Email
    asp .net 发邮件(带附件)测试可用
    ASP.NET图象处理详解
    DateTable全解
    带线的无限级下拉树列表
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3268503.html
Copyright © 2011-2022 走看看