輸入兩個整數 n 和 m,從數列1,2,3…….n 中 隨意取幾個數,
使其和等於 m ,要求將其中所有的可能組合列出來
排序 + 0-1揹包:
若第i個數放入,剩下0~i-1個數取出sum-ai
否則0~i-1取出sum
/**
* 從i個數里取出和為sum的組合個數
* 不去重
**@param i
*@param sum
*/private
static
intfun(int i, int sum, int a)
/*** 從i個數里取出和為sum的組合個數
* 去重
**@param i
*@param sum
*/private
static set> fun(int i, int sum, int a)
set> next1 = fun(i - 1, sum - a[i], a);
if (next1 != null)
ans.addall(next1);
}set> next2 = fun(i - 1, sum, a);
if (next2 != null)
return ans;
}
參考鏈結 和為給定數
總時間限制 1000ms 記憶體限制 65536kb 描述給出若干個整數,詢問其中是否有一對數的和等於給定的數。輸入共三行 第一行是整數n 0 n 100,000 表示有n個整數。第二行是n個整數。整數的範圍是在0到10 8之間。第三行是乙個整數m 0 m 2 30 表示需要得到的和。輸出若存在和為...
PTA 使用函式統計指定數字的個數
本題要求實現乙個統計整數中指定數字的個數的簡單函式。countdigit number,digit 其中number是整數,digit為 1,9 區間內的整數。函式countdigit應返回number中digit出現的次數。函式介面定義 countdigit number,digit 返回digi...
排列組合(包含所有組合可能和指定元素個數的組合)
當元素個數少時.元素組合方式 f 1 a a f 2 a,b b ba a f 3 a,b,c c cb cba ca b ba a f 4 a,b,c,d d dc dcb dcba dca db dba da c cb cba ca b ba a f n 由上表可以得出,n 個元素的所有組合方式...