查找数字位数之和等于给定值的数字
有一个数字 n 和一个值。我们必须找到所有 n 位数,其中所有 n 位数的和等于给定值。这里 0 不算作数字。
数字 n 必须在 1 到 100 的范围内,值必须在 1 到 500 的范围内。
输入和输出
Input: This algorithm takes number of digits, and the sum value. Let the digit count is 3. and sum is 15. Output: Display the number of different 3-digit numbers whose sum is 15. The result is 69. (There are 69 different 3-digit numbers whose sum is 15)
算法
count(digit, sum)
输入:数字的位数,给定值。
输出:计算有多少个数字。
Begin if digit = 0, then return true when sum = 0 if memTable[digit, sum] is not vacant, then return memTable[digit, sum] answer := 0 for i := 0 to 9 do if sum – i >= 0, then answer := answer + count(digit – 1, sum - i) done return memTable[digit, sum] := answer End
numberCount(digit, sum)
输入:数字的位数,给定值。
输出:有多少个这种类型的数字。
Begin define memTable and make all space vacant res := 0 for i := 1 to 9, do if sum – i >= 0, then res := res + count(digit – 1, sum - i) done return result End
示例
#include<iostream>
#define ROW 101
#define COL 501
using namespace std;
unsigned long long int memTable[ROW][COL];
unsigned long long int count(int digit, int sum) {
if (digit == 0) //for 0 digit number check if the sum is 0 or not
return sum == 0;
if (memTable[digit][sum] != -1) //when subproblem has found the result, return it
return memTable[digit][sum];
unsigned long long int ans = 0; //set the answer to 0 for first time
for (int i=0; i<10; i++) //count for each digit and find numbers starting with it
if (sum-i >= 0)
ans += count(digit-1, sum-i);
return memTable[digit][sum] = ans;
}
unsigned long long int numberCount(int digit, int sum) {
for(int i = 0; i<ROW; i++) //initially all entries of memorization table is -1
for(int j = 0; j<ROW; j++)
memTable[i][j] = -1;
unsigned long long int result = 0;
for (int i = 1; i <= 9; i++) //count for each digit and find numbers starting with it
if (sum-i >= 0)
result += count(digit-1, sum-i);
return result;
}
int main() {
int digit, sum;
cout << "Enter digit count: "; cin >> digit;
cout << "Enter Sum: "; cin >> sum;
cout << "Number of values: " << numberCount(digit, sum);
}输出
Enter digit count: 3 Enter Sum: 15 Number of values: 69
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP