33,008
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
const int MAX = 10;
int number[MAX], used[MAX], result[MAX];
int n;
void f(int l)
{
if(l==n)
{
for(int i=0; i < n; i++)
cout << result[i] << ' ';
cout << endl;
return ;
}
for(int i=0; i < n; i++)
{
if(used[i]>0)
{
used[i]--;
result[l] = number[i];
f(l+1);
used[i]++;
}
}
}
void readData()
{
int count=0, value;
cin >> n;
for(int i=0; i < n; i++)
{
cin >> value;
int j;
for(j=0; j < count;j ++)
{
if(number[j]==value)
{
used[j]++;
break;
}
}
if(j==count)
{
used[count]=1;
number[count++] = value;
}
}
}
int main()
{
readData();
cout << "Result is :" << endl;
f(0);
return 0;
}
至于第二题,就是一对多和多对一的问题,索引,建立关键字等一些东西都可以提高效率
Array.prototype.getCombination = function(m) {
var arr = [], q = this, n = q.length;
~function(o, i, j, n, m) {
if (m == 0) {
arr.push(o.join(""));
return
}
for (; q[j]; j ++) {
o[i] = q[j];
arguments.callee(o, i + 1, 0, n, m - 1);
}
}([], 0, 0, n, m);
return arr
}
TEST:
<textarea id="show" style="width:500px;height:500px"></textarea>
<script type=text/javascript>
Array.prototype.getCombination = function(m) {
var arr = [], q = this, n = q.length;
~function(o, i, j, n, m) {
if (m == 0) {
arr.push(o.join(""));
return
}
for (; q[j]; j ++) {
o[i] = q[j];
arguments.callee(o, i + 1, 0, n, m - 1);
}
}([], 0, 0, n, m);
return arr
}
document.getElementById("show").innerHTML = "0123456789abcdefghijklmnopqrstuvwxyz".split("").getCombination(3).join(",");
</script>
Array.prototype.getCombination = function(k) {
var arr = [], q = this, n = q.length;
~function(o, i, j, k) {
if (k == 0) {
arr.push(o.join(""));
return
}
while (q[j]) {
o[i] = q[j], j ++;
arguments.callee(o, i + 1, 0, k - 1);
}
}([], 0, 0, k);
return arr
}
TEST:
<textarea id="show" style="width:600px;height:500px"></textarea>
<script type=text/javascript>
Array.prototype.getCombination = function(k) {
var arr = [], q = this, n = q.length;
~function(o, i, j, k) {
if (k == 0) {
arr.push(o.join(""));
return
}
while (q[j]) {
o[i] = q[j], j ++;
arguments.callee(o, i + 1, 0, k - 1);
}
}([], 0, 0, k);
return arr
}
document.getElementById("show").innerHTML = "0123456789abcdefghijklmnopqrstuvwxyz".split("").getCombination(3).join(",");
</script>